单链表的就地逆置----头插法
图解
关于代码
#include<stdio.h>
#include<stdlib.h>struct Node
{
int data;
struct Node *next;
};
int icount=0;
struct Node* Create() //链表的创建
{
struct Node *head;
struct Node *p,*q;
int data;
p=head;
head->next=NULL;
scanf("%d",&data);
while(data!=-1)
{
q=(struct Node *)malloc(sizeof(struct Node));
q->data=data;
q->next=p->next;
p->next=q;
p=q;
scanf("%d",&data);
}
return head;
}
void Insert(struct Node *head) //链表的就地逆置
{
struct Node *p; //定义一个用来遍历链表的指针
struct Node *q;
p=head->next;
head->next=NULL;//头指针的下一节点为空
while(p){
q=p; //将p所指向的值存到q中
p=p->next; //p结点向后移一个
q->next=head->next; //q节点的下一个指针为空(头结点的下一个指针为空)
head->next=q; //q节点中存储的数插到头指针的后面
}
}
int print(struct Node* head) //链表的输出
{
struct Node *ptemp;
ptemp=head->next;
while(ptemp!=NULL)
{
printf("%d",ptemp->data);
ptemp=ptemp->next;
}
}
int main(void)
{
struct Node* head;
head=Create();
Insert(head);
print(head);
return 0;
}
关于思想(头插法)
1)创建两个指针,一个用来遍历链表,另一个用来存储数据。(*p,*q)
2)断开头指针和它的下一个节点,令头指针的下一个节点为空。
3 )为节点q开辟一个新的空间,将第一个节点中的值存到p中。(防止数据丢失)
4)q节点的下一个指针为空,将q中的数据插到头指针的后面。
5)p节点遍历。