单链表的逆置
简单的单链表逆置操作,图中黑色节点只能找到有颜色的节点、或通过箭头找到节点。
#include<stdio.h> #include <stdlib.h> typedef struct _Node { struct _Node* next; int data; }Node; void Print(Node* cur) { for(;cur->next!=NULL;cur=cur->next) { printf("%d ",cur->data); } printf("%d\n",cur->data); } //cur图中实黑色节点 Node* Reverse(Node* cur) { Node* pre;//图中蓝色节点 Node* next;//图中红色节点 pre = cur;//第一个标蓝 cur = cur->next;//实节点后移 pre->next = NULL;//头节点指向null for(;cur!=NULL;) { next = cur->next;//标红节点 cur->next = pre;//实节点箭头调转 pre = cur;//蓝节点后移 cur = next;//实节点后移 } return pre; } int main(int argc, char** argv) { int len = 0; do { printf("请输入链表的长度:\n"); fflush(stdin); scanf("%d",&len); }while(len == 0); printf("请输入链表的数据:\n"); Node* head = NULL; Node* cur = NULL; for(int i=0;i<len;i++) { Node* node = (Node*)malloc(sizeof(Node)); node->next = NULL; if(head == NULL) { head = node; cur = head; } else { cur->next = node; cur = node; } int res = 0; while(0 == res) { fflush(stdin); res = scanf("%d",&node->data); } } Print(head); head = Reverse(head);//逆置操作 Print(head); }
当然,如果用递归的话,可以找到链表的尾巴,然后一个一个的往上一层修改链接的方向,直到整个链表方向置返。看上去将会更加直观。
#include<stdio.h> #include <stdlib.h> typedef struct _Node { struct _Node* next; int data; }Node; void Print(Node* cur) { for(;cur->next!=NULL;cur=cur->next) { printf("%d ",cur->data); } printf("%d\n",cur->data); } Node* Reverse(Node* cur) { if(cur == NULL)//传入就为null { return NULL; } if(cur->next == NULL)//传入已是尾节点,可以与上面的合并 { return cur; } Node* head = Reverse(cur->next);//链表逆置后的head cur->next->next = cur;//直到倒数第二个节点才到这里 return head; } int main(int argc, char** argv) { int len = 0; do { printf("请输入链表的长度:\n"); fflush(stdin); scanf("%d",&len); }while(len == 0); printf("请输入链表的数据:\n"); Node* head = NULL; Node* cur = NULL; for(int i=0;i<len;i++) { Node* node = (Node*)malloc(sizeof(Node)); node->next = NULL; if(head == NULL) { head = node; cur = head; } else { cur->next = node; cur = node; } int res = 0; while(0 == res) { fflush(stdin); res = scanf("%d",&node->data); } } Print(head); Node* tmphead = head; head = Reverse(head);//递归逆置操作 tmphead->next = NULL;//原链表头变为了尾 Print(head); }