需求:
实现对单链表的反转
代码实现:
#include <stdio.h>
typedef struct node{
int data;
struct node* next;
}NODE;
void PrintLink(NODE* phead)
{
NODE* p = phead;
while(p != NULL){
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
NODE* Iteration(NODE* phead)
{
int i;
NODE* p = phead;
NODE* newhead = NULL; //定义一个 新的头节点为NULL,目的是为了把逆序后的t1->next改为NULL;后续再将newhead更新为p偏移;
NODE* temp;
while(p != NULL){
temp = p->next; //备份p->next以避免找不到,形成不了偏移;
p->next = newhead; //将p->next修改为其前一个节点;
newhead = p; //在p偏移前将其赋值给newhead,确保返回的newhead是正确的;方便后续打印反转后的链表;
p = temp;
}
return newhead;
}
int main()
{
NODE t5 = {5,NULL};
NODE t4 = {4,&t5};
NODE t3 = {3,&t4};
NODE t2 = {2,&t3};
NODE t1 = {1,&t2};
NODE* head = &t1;
printf("链表反转前:\n");
PrintLink(head);
printf("链表反转后:\n");
head = Iteration(head);
PrintLink(head);
return 0;
}
打印: