链表用节点存储数据,其节点中有存放数据的变量,也存放着指向下一个节点地址的指针。
1 typedef int elemtype; 2 3 typedef struct node{ 4 elemtype date; 5 struct node *next; 6 }LinkedList;
链表初始化有2种方法,头插法建立和尾插法建立。头插法:插入第一个元素到头结点之后,下一个元素插到当前元素之前,后面依次。尾插法:插入第一个元素到头结点之后,
1 LinkedList *init_LinkedListH(){//头插法 2 3 LinkedList *head = (LinkedList *)malloc(sizeof(LinkedList)); 4 if(head==NULL) 5 return NULL; 6 7 head->next = NULL; 8 9 LinkedList *p; 10 elemtype e; 11 printf("输入非0常数: "); 12 scanf("%d",&e); 13 while(e!=0){ 14 p = (LinkedList *)malloc(sizeof(LinkedList)); 15 if(p==NULL) 16 return NULL; 17 18 p->date = e; 19 p->next = head->next; 20 head->next = p; 21 22 scanf("%d",&e); 23 } 24 return head; 25 26 }
1 LinkedList *init_LinkedListT(){//尾插法 2 3 LinkedList *p,*tail; 4 LinkedList *head = (LinkedList *)malloc(sizeof(LinkedList)); 5 if(head==NULL) 6 return NULL; 7 8 head->next=NULL; 9 tail = head; 10 11 elemtype e; 12 printf("输入非0常数: "); 13 scanf("%d",&e); 14 while(e!=0){ 15 16 p = (LinkedList *)malloc(sizeof(LinkedList)); 17 if(p==NULL) 18 return NULL; 19 p->date = e; 20 tail->next = p; 21 tail = p; 22 tail->next = NULL; 23 scanf("%d",&e); 24 } 25 return head; 26 27 }
链表方便插入和删除节点。插入分为前插和后插
1 //前插运算 把头指针和某节点指针传入,*s为待插入节点 2 void insertBefore(LinkedList *p,LinkedList *s,LinkedList *head){ 3 4 LinkedList *temp = head; 5 while(temp->next!=p){ 6 temp = temp->next; 7 } 8 9 s->next = p; 10 temp->next = s; 11 12 } 13 14 //后插运算 p为指向链表中某个节点的指针 .*s为待插入节点 15 void insertAfter(LinkedList *p,LinkedList *s){ 16 17 s->next = p->next; 18 p->next = s; 19 20 }
删除分为后继节点删除和删除本身节点,后继节点删除先判断后继节点是否存在,若存在则删除。而删除本身节点的思路则是先判断后继节点是否存在,若存在则把后继节点元素值赋给本身节点,再调用后继节点删除函数删除后继节点;若不存在则找到本身节点的上一个节点,在调用后继节点删除函数删除后继节点。尽量避开从头结点开始的遍历运算。
1 //删除后继节点 2 int deleteAfter(LinkedList *p) { 3 4 LinkedList *q = p->next; 5 if(q==NULL) 6 return 0; 7 p->next = q->next; 8 free(q); 9 return 1; 10 } 11 12 //删除节点本身 13 int deleteNode(LinkedList *head,LinkedList *p){ 14 15 int deleteAfter(LinkedList *p); 16 17 if(p->next!=NULL){ 18 p->date = p->next->date; 19 return (deleteAfter(p)); 20 } 21 else{ 22 LinkedList *q = head; 23 while(q->next!=p) 24 q = q->next; 25 q->date = p->date; 26 return (deleteAfter(q)); 27 } 28 29 }