链表逆置:
1:先用一个newroot指向链表头结点;
2:用curr指向头结点的下一个节点,nextnode指向curr的下一个节点,用来更新curr;
3:断开头结点与链表的链接;
4:循环头插法把curr插入newnode为头结点的链表;
5:curr更新为下一个节点;
代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node*next;
}Node, *Ls;
Node*BuyNode(Node*p)
{
p = (Node*)malloc(sizeof(Node));
if(p==NULL)exit(-1);
p->next = NULL;
return p;
}
//
Node*CreateNode(int val)
{
Node*p = (Node*)malloc(sizeof(Node));
if(p==NULL)exit(-1);
p->data = val;
p->next =NULL;
return p;
}
Node* Init(Node* p)//初始化,malloc一个头结点
{
return BuyNode(p);
}
void Insert(Ls list, int val)//头插法
{
Node *p = CreateNode(val);
p->next = (list)->next;
(list)->next = p;
}
void show(Ls list)
{
if(list==NULL)
{
return ;
}
Node *p = (list)->next;
for( ; p !=NULL; p=p->next)
{
printf("%d ",p->data);
}
printf("\n");
}
//逆置
void Reverse(Node*ls)
{
if(ls==NULL)
{
return ;
}
Node*newroot = ls;//newroot指向原来的头结点;
Node*curr = ls->next;//curr指向头结点的下一个节点;
Node*nextnode = NULL;//声明curr的下一个节点
newroot->next = NULL;//断开的头结点与原来的链表,next域置为空;
while(curr != NULL)
{
nextnode = curr->next;//curr的下一个节点
curr->next = newroot->next;//连接到新的头结点;
newroot->next = curr;
curr = nextnode; //原来的结点向后移动
}
}
int main()
{
Node root;
Node* p =Init(&root);//头结点
for(int i=0;i<10;++i)
{
Insert(p,i);
}
show(p);
Reverse(p);
show(p);
return 0;
}
结果:
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
请按任意键继续…