單鏈表逆轉


單鏈表逆轉算法草圖如下:

 

方法1:借助輔助空間

建立臨時的新鏈表,將新節點指向其前驅結點實現逆轉:

#include <stdio.h> #include <conio.h> #include<malloc.h>
//#include "alloc.h"
 typedef struct  /* 使用typedef定義類型 */ { char x; struct node * next; } node; node * input() { node *p1,*p2,*h=NULL; char ch; while(1) { ch=getche(); if(ch=='\r') break; p1=(node *)malloc(sizeof(node)); p1->x=ch; if(h==NULL) h=p1; else p2->next=p1; p2=p1; } p1->next=NULL; return h; } void display(node *p) { printf("\n"); while(p!=NULL) { putchar(p->x); p=p->next; } } node * reverse(node * p) { node * p1=NULL,*p2; while(p!=NULL) { p2=(node *) malloc(sizeof(node)); if(p1==NULL) p2->next=NULL; /* 逆轉之后,原鏈表的頭結點就是新鏈表的尾結點 */
        else p2->next=p1;    /* 如果不是第一個結點,則本次產生的新結點是上次結點的前一個 */ p1=p2; p2->x=p->x; p=p->next; } return p1;  /*原鏈表的最后一個結點是新鏈表的頭結點 */ } int main(void) { node * head,* h2; head=input(); display(head); h2=reverse(head); display(h2); getch(); return 0; }

 

方法2:原地逆轉

頭尾互換,指針指向反轉

#include <stdio.h> #include <conio.h> #include <malloc.h>

struct node { char x; struct node * next; }; struct node * input() { struct node *p1,*p2,*h=NULL; char ch; while(1) { ch=getche(); if(ch=='\r') break; p1=(struct node *)malloc(sizeof(struct node)); p1->x=ch; if(h==NULL) h=p1; else p2->next=p1; p2=p1; } p1->next=NULL; return h; } void display(struct node *p) { printf("\n"); while(p!=NULL) { putchar(p->x); p=p->next; } } struct node * reverse(struct node *h) { struct node *p=h,*q=NULL,*listend=h; while(listend->next!=NULL) listend=listend->next; while(p!=listend) { h=p->next; listend->next=p; if(q==NULL) p->next=NULL; else p->next=q; q=p; p=h; } return h; } int main(void) { struct node * head; head=input(); head=reverse(head); display(head); getch(); return 0; }

 

思考:

單鏈表的逆轉如上都是采用循環遍歷的方法,那應該也可采用遞歸遍歷的方法吧?  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM