不带头结点的链表操作----插入删除打印

#include<stdio.h>

#include<stdlib.h>

typedef struct list

{

 int data;

 struct list*next;

}List;

List*insert_list_2nd(List*head,int data);

List*insert_list_last(List*head,int data);

List*insert_list_order(List*head,int data);

void print_list(List*head);

List*delete_list(List*head,int value);

int main()

{

 List*head=NULL; 

 int i;

// for(i=0;i<10;i++)

 // head=insert_list_2nd(head,i);

 // head=insert_list_last(head,i);

 for(i=9;i>=0;i--)

  head=insert_list_order(head,i); 

 print_list(head); 

 for(i=0;i<9;i++)

  head=delete_list(head,i);

 print_list(head); 

}

List*insert_list_2nd(List*head,int data)

{

 List*newnode=(List*)malloc(sizeof(List));

 newnode->data=data;

/* if(head==NULL)

 {

  head=newnode;

  newnode->next=NULL; 

 } 

 else

 {

  newnode->next=head;

  head=newnode;

 }*/

 newnode->next=head;

 head=newnode; 

 return head;

}

List*insert_list_last(List*head,int data)

{ List*newnode=(List*)malloc(sizeof(List));

 List*temp=head; 

 newnode->data=data;

 newnode->next=NULL;

 if(head==NULL) return newnode; 

 while(temp->next)

 {

  temp=temp->next; 

 }  

 temp->next=newnode;

 return head;

}

List*insert_list_order(List*head,int data)

{

 List*temp=head;

 List*newnode=(List*)malloc(sizeof(List));

 newnode->data=data;

 newnode->next=NULL;

 if(head==NULL) //链表为空为空 

 {

  return newnode;

 }

 if(head->data>data)//链表第一个节点就是要插入的位置 

 {

  newnode->next=head;

  return newnode;

 }

 while(temp->next && temp->next->data<data)

 {

  temp=temp->next;

 }

/* if(temp->next==NULL)

 {

  temp->next=newnode;

 }   

 else

 {

  newnode->next=temp->next;

  temp->next=newnode;

 }*/

 newnode->next=temp->next;

 temp->next=newnode;

 return head;

}

void print_list(List*head)

{

 while(head)

 {

  printf("%d\n",head->data);

  head=head->next;

 } 

}

List*delete_list(List*head,int value)

{ List*temp;

 List*p;

 if(head==NULL) return NULL;

 if(head->data==value)

 {

  temp=head->next;

  free(head);

  return temp; 

 }

 temp=head;

 while(temp->next && temp->next->data!=value)

 {

  temp=temp->next; 

 }  

 //p=temp->next;

 if(temp->next==NULL)

 {

  printf("no have %d\n",value);

  return head;

 }

 else

 {

  p=temp->next;

  temp->next=temp->next->next;

  free(p);

  return head;

 }

 

} 

  

你可能感兴趣的:(链表)