當前位置:首頁 » 操作系統 » 鏈表逆序的演算法

鏈表逆序的演算法

發布時間: 2024-09-09 16:45:46

1. C語言用鏈表實現逆序輸出

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

//定義鏈表節點
typedefstructLNode
{intdata;
structLNode*next;
}LNode,*Linklist;

//創建鏈表
Linklistcreate()
{inti,n;//i用於下面循環,n用來存放有效節點的字數
Linklistp,L;
printf("PleaseinputN=");
scanf("%d",&n);
L=(Linklist)malloc(sizeof(LNode));//分配一個不存放有效數據的頭結點
L->next=NULL;
for(i=0;i<n;i++)
{p=(Linklist)malloc(sizeof(LNode));//生成新節點
scanf("%d",&p->data);//輸入元素值
p->next=L->next;
L->next=p;
}
returnL;//返回頭節點;
}
//鏈表反轉輸出
LinklistReverseList(LinklistL,intst)//st為1時輸出結點數據
{if(L->next!=NULL)
ReverseList(L->next,1);
if(st)printf("%d",L->data);
returnL;
}

voidput(LinklistL)
{Linklistp;
p=L->next;
while(p!=NULL)
{printf("%d",p->data);
p=p->next;
}
printf(" ");
}

intmain()
{LinklistL;
L=create();
printf("A:");put(L);
printf("B:");
ReverseList(L,0);//附加結點未保存數據,故第二參數為0
return0;
}

2. 已知鏈表的頭結點head,寫一個函數把這個鏈表逆序。C++ 代碼不是看得很懂。

這個程序的原理就是:假如本來有0-10數(0是頭結點,不考慮逆置)按正常順序排列,現在我把1後面的數斷開,這樣鏈表只剩下0->1了。接下來,我把2插入到鏈表中,就變成了0->2->1,然後在插入3,就變成0->3->2->1,類推,實現1-10的逆置。程序中的p2和p3都是過渡用的結點,你再仔細理解下。

熱點內容
河南科技大學期末編譯原理試題 發布:2025-07-12 19:53:17 瀏覽:46
電腦中的微信聊天記錄在哪裡存儲 發布:2025-07-12 19:47:22 瀏覽:944
蘋果6sp怎麼設置密碼 發布:2025-07-12 19:28:50 瀏覽:547
電視下架緩存的還能看嗎 發布:2025-07-12 19:14:12 瀏覽:444
安卓平板微軟平板和蘋果哪個好 發布:2025-07-12 19:09:37 瀏覽:413
資料庫地區 發布:2025-07-12 19:05:41 瀏覽:395
如何檢查vds腳本 發布:2025-07-12 19:04:24 瀏覽:909
命令行編譯vs2013 發布:2025-07-12 19:01:22 瀏覽:809
c語言輸出所有素數 發布:2025-07-12 19:01:19 瀏覽:659
查電費賬號密碼多少 發布:2025-07-12 18:56:19 瀏覽:545