原题地址
http://codeup.hustoj.com/problem.php?cid=100000607&pid=4
解题思路
刚开始还是不太懂咋做,然后选择把原来链表里的元素每个都换个方向指。
就一开始相当于我们先创建个pre
的结点,其地址是NULL
,这个就作为我们反转之后链表的末尾了,然后从头结点之后的第一个结点开始,pre向右边移, 每一个都往pre
指。
最后输出的时候我为了方便,给反转之后的链表加了一个叫做newhead
的头结点~
参考代码
#include <bits/stdc++.h>
using namespace std;
#define pb push_back;
typedef double db;
typedef long long LL;
typedef vector<int> VI;
const int inf = 2e9;
const LL INF = 8e18;
const int maxn = 5e5 + 5;
struct node{
int data;
node* next;
};
node* create(VI a) {
node* head, *p, *pre;
head = new node;
head->next = NULL;
pre = head;
for (int i = 0; i < a.size(); i++) {
p = new node;
p->data = a[i];
p->next = NULL;
pre->next = p;
pre = p;
}
return head;
}
node* reverse(node* head) {
node* pre = NULL, *next = NULL, *p = head->next;
if (head == NULL || head->next == NULL) return head;
while (p != NULL) {
next = p->next;
p->next = pre;
pre = p;
p = next;
}
return pre;
}
void printl(node* head) {
node* L = head->next;
while (L != NULL) {
cout << L->data;
L = L->next;
if (L != NULL) cout << ' ';
}
}
int main() {
int k;
while (~scanf("%d", &k)) {
if (k == 0) cout << "list is empty" << endl;
else {
VI a(k);
for (int i = 0; i < k; i++) {
cin >> a[i];
}
node* head = create(a);
printl(head);
cout << endl;
node* newh = reverse(head);
node* newhead = new node;
newhead->next = newh;
printl(newhead);
cout << endl;
}
}
return 0;
}