链表反转
作者:
兜里没有钢镚
,
2022-05-18 02:15:09
,
所有人可见
,
阅读 238
倒放
#include<bits/stdc++.h>
using namespace std;
struct Node {
int value;
Node *next;
} a[100010],*head,*tail,*p1,*p2;
int main ()
{
int n;
head = tail = NULL;
cin>>n;
for(int i=1;i<=n;i++) {
cin>>a[i].value;
if(head == NULL)tail = head = &a[i];
else {
tail ->next = &a[i];
tail = &a[i];
}
}
Node *x,*y,*z; //三个变量用于指针交换
x = head,y = x->next; //先找到x y 箭头的交换必须有第三个元素出现
head ->next = NULL;//初始的时候把原来头指针指向第一个元素改为指向空指针
while(y) {//y有值的情况下
z = y->next; //先找到y的下一个
y ->next = x; //y指向x
x = y; //更替
y = z; //更替
}
head = x; //头指向x 原因是因为循环到最后y为空 只剩下x
for(Node *p = head;p;p=p->next) {
cout<<p->value<<endl;
}
return 0;
}