1. 程式人生 > >單鏈表實現反轉的三種方法

單鏈表實現反轉的三種方法

單鏈表的操作是面試中經常會遇到的問題,今天總結一下反轉的幾種方案:

1 ,兩兩對換
2, 放入陣列,倒置陣列
3, 遞迴實現

程式碼如下:

#include<stdio.h>
#include<malloc.h>
typedef struct Node
{

    int data;
    struct Node *pnext;


} Node,*pnode;
pnode CreateNode()
{

    pnode phead=(pnode)malloc(sizeof(Node));
    if(phead==NULL)
    {
        printf
("fail to allocate memory"); return -1; } phead->pnext=NULL; int n; pnode ph=phead; for(int i=0; i<5; i++) { pnode p=(pnode)malloc(sizeof(Node)); if(p==NULL) { printf("fail to allocate memory"); return -1; } p->data=(i+2
)*19; phead->pnext=p; p->pnext=NULL; phead=phead->pnext; } return ph; } int list(pnode head) { int count=0; printf("遍歷結果:\n"); while(head->pnext!=NULL) { printf("%d\t",head->pnext->data); head=head->pnext; count++; } printf
("連結串列長度為:%d\n",count); return count; } pnode reverse2(pnode head)//兩兩節點之間不斷交換 { if(head == NULL || head->next == NULL) return head; pnode pre = NULL; pnode next = NULL; while(head != NULL){ next = head->next; head->next = pre; pre = head; head = next; } return pre; } void reverse1(pnode head,int count)//把連結串列的節點值放在陣列中,倒置陣列 { int a[5]= {0}; for(int i=0; i<count,head->pnext!=NULL; i++) { a[i]=head->pnext->data; head=head->pnext; } for(int j=0,i=count-1; j<count; j++,i--) printf("%d\t",a[i]); } pnode reverse3(pnode pre,pnode cur,pnode t)//遞迴實現連結串列倒置 { cur -> pnext = pre; if(t == NULL) return cur; //返回無頭節點的指標,遍歷的時候注意 reverse3(cur,t,t->pnext); } pnode new_reverse3(pnode head){ //新的遞迴轉置 if(head == NULL || head->next == NULL) return head; pnode new_node = new_reverse3(head->next); head->next->next = head; head->next = NULL; return new_node; //返回新連結串列頭指標 } int main() { pnode p=CreateNode(); pnode p3=CreateNode(); int n=list(p); printf("1反轉之後:\n"); reverse1(p,n); printf("\n"); printf("2反轉之後:\n"); pnode p1=reverse2(p); list(p1); p3 -> pnext = reverse3(NULL,p3 -> pnext,p3->pnext->pnext); printf("3反轉之後:\n"); list(p3); free(p); free(p1); free(p3); return 0; }

這裡注意: head ->next = pre; 以及 pre = head->next,前者把head->next 指向 pre,而後者是把head->next指向的節點賦值給pre。如果原來head->next 指向 pnext節點,前者則是head重新指向pre,與pnext節點斷開,後者把pnext值賦值給pre,head與pnext並沒有斷開。