思路很简单,每次取两个结点,使后一个结点指向前一个结点,再用一个变量保存后面剩余的链表,每次移动一位,最后把剩下的两个连起来,但是很容易错,next指针很难弄清楚。
#pragma warning(disable:4996)
#include<iostream>
#include<cstring>
#include<cstdio>
#include<climits>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
using namespace std;
typedef long long ll;
typedef int datatype;
struct node
{
datatype info;
struct node* next;
};
node* init()
{
return NULL;
}
//头插法
node* insert_head(node* head, int x)
{
node* p;
p = (node*)malloc(sizeof(node));
p->info = x;
p->next = head;
head = p;
return head;
}
//尾插法
node* insert_tail(node* head, int n)
{
int i, t;
head = (node*)malloc(sizeof(node));
node* end, * temp;
end = head;
for (i = 0;i < n;i++)
{
temp = (node*)malloc(sizeof(node));
scanf("%d", &t);
temp->info = t;
end->next = temp;
end = temp;
}
end->next = NULL;
return head->next;
}
void display(node* head)
{
node* p = head;
if (p == NULL)
{
printf("链表是空的\n");
return;
}
while (p)
{
printf("%d ", p->info);
p = p->next;
}
printf("\n");
}
node* reverse(node* head)
{
if (head == NULL)
{
printf("链表是空的\n");
return NULL;
}
node* p, * q = head, * r;
p = q->next;r = p->next;
//q代表第一个结点,p代表第二个,r代表剩下的链表
q->next = NULL;
while (r)
{
//p->next = NULL;表示和剩下的链表断裂,不加这句也可以
p->next = q;//连接到q上
q = p;
p = r;
r = r->next;//后移一位,顺序很重要
}
p->next = q;//把最后剩下的连起来
return p;
}
int main()
{
int n, i, j, val, x, y;
node* head = NULL;
printf("输入结点个数:");
scanf("%d", &n);
head = insert_tail(head, n);
printf("链表从头到尾:");
display(head);
head = reverse(head);
printf("逆转后:");
display(head);
return 0;
}