鏈表的頭尾倒置的一種方法

   鏈表的頭尾倒置用的方法其實使用的就是鏈表的頭插入法。

   我們在利用頭插法生成一個鏈表時候,會發現最先插入的數據,往往會把它放到鏈表數據的尾端。因此我們可以利用這個性質把鏈表元素再進行一次頭插法,這樣可以實現鏈表的頭尾倒置。

   具體方法。設置兩個新的指針,分別指向元素的首個結點和首結點的下個結點。這樣的話在頭結點後面打斷鏈表的時候,兩個指針,我們可以實現一個指針開始插入數據,一旦插入的話就會打斷之後的關係,第二個指針記錄後面的位置信息。然後依次把這兩個指針後移,實現遍歷整個鏈表實現頭尾倒置。

具體驗證代碼如下:

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


typedef struct Node
{
int data;
struct Node *next;
}NODE;


NODE *creatListHead()
{
NODE *head = (NODE *)malloc(sizeof(NODE));
head->next = NULL;

return head;
}


void creatListBody(NODE *head, int data)
{
NODE *cur = (NODE *)malloc(sizeof(NODE));
cur->data = data;
cur->next = head->next;
head->next = cur;
}


void printList(NODE *head)
{
head = head->next;

while(head)
{
printf("%d\n",head->data);
head = head->next;
}
}


int lenList(NODE *head)
{
head = head->next;
int len = 0;
while(head)
{
len++;
head = head->next;
}
return len;
}


void reserveList(NODE *head)
{
NODE *cur= head->next;
NODE *pt = cur->next;
head->next = NULL;

while(1)
{
cur->next = head->next;
head->next = cur;
cur =pt;
if(NULL == cur)
{
break;
}
pt=pt->next;

}

 } 
int main(void)
{
//創建一個鏈表的頭結點指針 
NODE *head = creatListHead();
//以頭結點後面插入的方法插入鏈表數據 
for(int i=0; i<20;i++)
{
creatListBody(head,i);
}
//打印出鏈表數據 
printList(head);
printf("===============================\n");
//計算鏈表的長度,並打印出來。 
int len = lenList(head);
printf("The lens of the List is %d\n",len);
//倒置鏈表的頭與尾並打印出來。 
reserveList(head);
printList(head);

return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章