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

鏈表逆序的演算法

發布時間: 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都是過渡用的結點,你再仔細理解下。

熱點內容
php日誌查看 發布:2025-07-12 16:12:10 瀏覽:211
ftp目錄映射為本地盤符 發布:2025-07-12 16:06:59 瀏覽:642
nas存儲百科 發布:2025-07-12 16:03:17 瀏覽:123
python的sort函數 發布:2025-07-12 15:53:21 瀏覽:48
ensp伺服器怎麼設置web根目錄 發布:2025-07-12 15:47:56 瀏覽:283
安卓怎麼設置二卡發信息 發布:2025-07-12 15:43:50 瀏覽:742
如何看到無線密碼 發布:2025-07-12 15:43:13 瀏覽:674
好網址可緩存 發布:2025-07-12 15:36:07 瀏覽:251
centos安裝php52 發布:2025-07-12 15:14:19 瀏覽:298
usb介面編程 發布:2025-07-12 15:14:19 瀏覽:215