链表的头尾倒置的一种方法

   链表的头尾倒置用的方法其实使用的就是链表的头插入法。

   我们在利用头插法生成一个链表时候,会发现最先插入的数据,往往会把它放到链表数据的尾端。因此我们可以利用这个性质把链表元素再进行一次头插法,这样可以实现链表的头尾倒置。

   具体方法。设置两个新的指针,分别指向元素的首个结点和首结点的下个结点。这样的话在头结点后面打断链表的时候,两个指针,我们可以实现一个指针开始插入数据,一旦插入的话就会打断之后的关系,第二个指针记录后面的位置信息。然后依次把这两个指针后移,实现遍历整个链表实现头尾倒置。

具体验证代码如下:

#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;
}




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