反转链表
题目描述
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
- 链表中节点的数目范围是
[0, 5000]
-5000 <= Node.val <= 5000
代码如下:
核心代码模式:
核心代码模式大家应该都懂,就不详细分析了。网上随便找一堆讲解的。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* tmp;
ListNode* cur = head;
ListNode* pre = nullptr;
while(cur) {
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
delete tmp;
return pre;
}
};
ACM代码模式:
大家可能会对ACM模式有些困扰
链表的基本键盘输入实现
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
int main() {
int num;
cin >> num;
ListNode* head=new ListNode(num);//创建链表头
ListNode* ptr = head;//一般不会在原链表上直接操作,创建指向head的ptr,对ptr进行操作
while (cin.get() != '\n') {
cin >> num;
ptr->next = new ListNode(num);
ptr = ptr->next;
}
while (head) {//遍历输出,最后可以删除
if (head->next == NULL)
cout << head->val << "-> NULL";
else
cout << head->val << "-> ";
head = head->next;
}
}
我们来看一下效果:
可以看到基本的键盘输入输出实现都没问题。下面在此基础上实现反转链表。
反转链表
基本就是在上面代码的基础上调用一下reverseList函数,注意这里要用一个头节点接住函数返回的链表,然后输出。
代码如下:
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* reverseList(ListNode* head) {
ListNode* tmp;
ListNode* cur = head;
ListNode* pre = nullptr;
while(cur) {
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
delete tmp;
return pre;
}
int main() {
int num;
cin >> num;
ListNode* head = new ListNode(num);
ListNode* ptr = head;
while(cin.get() != '\n') {
cin >> num;
ptr->next = new ListNode(num);
ptr = ptr->next;
}
head = reverseList(head);
while (head) {//遍历输出
if (head->next == NULL)
cout << head->val << "-> NULL";
else
cout << head->val << "-> ";
head = head->next;
}
system("pause");
return 0;
}
效果如下所示:
自己也是因为要找工作所以最近开始学习用ACM模式做题,欢迎大家一起交流讨论!