1. 先保存原有的next
2. 将next指向前一节点
3. 指针指向尚未反转的节点 重复操作
#include <iostream>
#include <stdio.h>
typedef struct myNode
{
int data;
myNode *next;
}myNode;
myNode* create()
{
int i = 0;
myNode* head, *p, *q = nullptr;
int x = 0;
head = (myNode*)malloc(sizeof(myNode));
while (true)
{
printf("Please input the data: ");
scanf_s("%d", &x);
if (0 == x)
{
break;
}
p = (myNode*)malloc(sizeof(myNode));
p->data = x;
if (++i == 1)
{
head->next = p;
}
else
{
q->next = p;
}
q = p;
}
q->next = nullptr;
return head;
}
// 1 2 3
myNode* reverse(myNode* head)
{
myNode* pLeft, *pRight, *pTemp;
if (head->next == nullptr)
return head;
/* pLeft此时指向了1 pRight此时指向了2 获取到next后,将1作为尾节点 next置空*/
pLeft = head->next;
pRight = pLeft->next;
pLeft->next = NULL;
while (pRight != nullptr)
{
// 将要替换的节点的next保存,然后将next指向前一节点 原本2的next应为3 此时保存3之后,需要将2的next指向1
pTemp = pRight->next;
pRight->next = pLeft;
// 此时上面的语句已经完成了当前两个节点的逆转操作,所以left right就要指向下一个需要逆转的节点
pLeft = pRight;
pRight = pTemp;
}
// head 本来就是一个空节点,当链表完成反转后,将head->next 指向left即可 循环最后一次 pTemp应该为空 所以不能指向pRight
head->next = pLeft;
return head;
}
void printList(myNode* head)
{
myNode *p = head->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
}