链表逆序
链表逆序思路分析:
(1)如果链表为NULL,则不需要逆序
(2)不为空的话就,则设置三个指针,一个为current,一个为pnext,pnext(current->next)为current的后继,另外一个prev(current->next->next)0为pnext的后继
(3)循环current和pnext指针,直到penxt为空
(4)重新设置头指针,指向链表最后的一个节点
图示分析:
没逆序之前:
第一次变换:
第二次变换:
第三次变换:
重新设置头指针:
代码分析:
//链表逆序 void reverse(node *head) { node *pnext,*current,*prev; if(head == NULL || head->next == NULL) //空链表 return; current = head->next; //current初始化指向头节点 pnext = current->next; //pnext初始化指向头节点的后继节点 current->next = NULL; //把头节点的指针域初始化为空 while(pnext) { prev = pnext->next; //current->next->next pnext->next = current; //后一个节点指向前一个节点实现逆序 current = pnext; //current向后移动 pnext = prev; //pnext向后移动 } head->next = current; //重新设置头节点,形成逆序的链表 }
源代码:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 typedef struct Node 6 { 7 int data; 8 struct Node *next; 9 }node; 10 11 //初始化链表头 12 node* inti(node* head) 13 { 14 head = (node*)malloc(sizeof(node)); 15 head->data = 0; 16 head->next = NULL; 17 return head; 18 } 19 20 //插入生成节点 21 void create_new_node(node* head,int data) 22 { 23 node* new = (node*)malloc(sizeof(node)); 24 node* p; 25 p = head; 26 new->data = data; 27 if(head->next == NULL) 28 { 29 head->next = new; 30 new->next = NULL; 31 } 32 33 else 34 { 35 while(p->next) 36 p = p->next; 37 p->next = new; 38 new->next = NULL; 39 } 40 41 } 42 43 //显示链表 44 void display(node *head) 45 { 46 printf("the list node data:\n"); 47 node *p; 48 p = head->next; 49 while(p) 50 { 51 printf("%d\n",p->data); 52 p = p->next; 53 } 54 55 } 56 57 //删除节点 58 void delete_node(node* head,int data) 59 { 60 node *p,*q; 61 p = head; 62 q = p; 63 while(p) 64 { 65 if(p->next->data == data) 66 { 67 q->next = p->next->next; 68 break; 69 } 70 71 p = p->next; 72 q = p; 73 } 74 75 } 76 77 //链表逆序 78 void reverse(node *head) 79 { 80 node *pnext,*current,*prev; 81 if(head == NULL || head->next == NULL) //空链表 82 return; 83 current = head->next; //current初始化指向头节点 84 pnext = current->next; //pnext初始化指向头节点的后继节点 85 current->next = NULL; //把头节点的指针域初始化为空 86 87 while(pnext) 88 { 89 prev = pnext->next; //current->next->next 90 pnext->next = current; //后一个节点指向前一个节点实现逆序 91 current = pnext; //current向后移动 92 pnext = prev; //pnext向后移动 93 } 94 head->next = current; //重新设置头节点,形成逆序的链表 95 } 96 97 int main(int argc,char *argv[]) 98 { 99 node *head; 100 head = inti(head); 101 printf("create new node ,input 0 to qiut!!\n"); 102 int data; 103 while(1) 104 { 105 scanf("%d",&data); 106 if(data == 0) 107 break; 108 create_new_node(head,data); 109 } 110 display(head); 111 printf("please input integer which you want to delete:"); 112 scanf("%d",&data); 113 delete_node(head,data); 114 display(head); 115 printf("after reverse:\n"); 116 reverse(head); 117 display(head); 118 return 0; 119 }
View Code
运行结果: