首页 > 代码库 > 链表逆转的多种实现
链表逆转的多种实现
链表逆转的多种实现
链表的逆转是一种常见又较复杂的操作,下面使用多种方式进行实现:while、递归以及goto。
代码:
#include <stdio.h> #include <stdlib.h> //链表节点 typedef struct node { int data; struct node *next; }Node; //逆转的while实现 void rev(Node **list) //链表逆转 { if (*list == NULL || (*list)->next == NULL) //空或者只有一个节点 { return; } else { Node *pPre, *pCur, *pNext; pPre = *list; pCur = (*list)->next; while (pCur) { pNext = pCur->next; pCur->next = pPre; pPre = pCur; pCur = pNext; } (*list)->next = NULL; *list = pPre; } } //逆转的递归实现 void rev_r(Node **list, Node *pCur, Node *pNext) { if (pCur == NULL || pNext == NULL) { (*list)->next = NULL; *list = pCur; return; } rev_r(list, pNext, pNext->next); pNext->next = pCur; } //逆转的goto实现 void rev_goto(Node **list) { if (*list == NULL || (*list)->next == NULL) return; else { Node *pPre = *list; Node *pCur = (*list)->next; Node *pNext = NULL; stage: pNext = pCur->next; pCur->next = pPre; pPre = pCur; pCur = pNext; if (pCur) goto stage; (*list)->next = NULL; *list = pPre; } } void print(Node *list) { if (list == NULL) return; printf("%4d", list->data); print(list->next); } void main() //41 { Node p1 = { 1, NULL }; Node p2 = { 2, &p1 }; Node p3 = { 3, &p2 }; Node p4 = { 4, &p3 }; Node p5 = { 5, &p4 }; Node p6 = { 6, &p5 }; Node *list = &p6; printf("原链表\n"); print(list); printf("\n"); printf("逆转\n"); //rev(&list); //while //rev_r(&list, list, list->next); //递归 rev_goto(&list); //goto print(list); printf("\n"); system("pause"); }运行
链表逆转的多种实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。