题目描述
翻转一个链表
例如:1 2 3 4
输出:4 3 2 1
输入输出
输入
- 第一行是n; 表示链表长度
第二行是n个整数,表示链表每一位所存储的内容
输出- 针对每组输出,输出翻转后的链表的内容
示例输入
4
1 2 3 4
示例输出
4 3 2 1
题目分析
链表翻转是比较经典的面试题目,其中也有很多坑,要注意NULL和head节点的处理。
这道题有两种解法,迭代和递归,代码如下:
#include <iostream>
using namespace std;
class Node {
public:
int num;
Node *next;
Node():next(NULL) {}
Node(int num):num(num), next(NULL) {}
void display() {
Node *tmp = this;
while (tmp) {
printf("%d ", tmp->num);
tmp = tmp->next;
}
printf("\n");
}
};
class Reverse {
public:
Node* Iteration(Node* &head) {
Node *current = head;
Node *pre = NULL;
while (current != NULL) {
Node *next = current->next;
current->next = pre;
pre = current;
current = next;
}
return pre;
}
Node *Recursion(Node* &head) {
if (head == NULL || head->next == NULL) return head;
Node *newHead = Recursion(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
};
int main(int argc, char *argv[]) {
Node *head = NULL;
Node *current = NULL;
int n;
scanf("%d", &n);
while(n--) {
int num;
scanf("%d", &num);
Node *tmp = new Node(num);
if (head == NULL) head = tmp;
else current->next = tmp;
current = tmp;
}
Reverse re;
//head = re.Iteration(head);
head = re.Recursion(head);
head->display();
return 0;
}