题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
解题思路:
首先,链表中节点最重要的元素就是next指针,指向它的下一个节点;因此当需要反转链表时,其实只需要改变每个节点的next的指向就行。
步骤:
1.考虑特殊情况,当链表节点为空时,返回空指针nullptr;
2.定义两个链表节点指针:cur指向链表头节点,pre指向cur的前一个节点(注意当cur指向头结点时,pre为nullptr);
3.while循环,当cur没有指向最后一个节点时继续循环:
然后定义一个临时变量存储 cur的下一个节点的指针;
然后让cur指向当前节点的前一个节点;
让pre指向当前节点;
让cur指向下一个节点;
4. while时cur指向的是最后一个节点,pre指向的是倒数第二个节点,这时让cur的next域 等于pre,就是让最后一个节点的next域指向了倒数第二个节点;
5. 返回cur就行了。
代码如下:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr){
return nullptr;
}
ListNode* cur = pHead; //记录当前节点为头节点
ListNode* pre = nullptr; //头结点的前一个节点为空
while(cur->next != nullptr){
ListNode* temp = cur->next;
cur->next = pre; //当前节点的next指向它前一个节点
pre = cur; //移动pre指针
cur = temp; //移动当前节点到下一位
}
//循环结束时,cur指向最后一个节点,pre指向倒数第二个节点
cur->next = pre;
return cur;
}
};
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr){
return nullptr;
}
ListNode* cur = pHead; //记录当前节点为头节点
ListNode* pre = nullptr; //头结点的前一个节点为空
while(cur->next != nullptr){
ListNode* temp = cur->next;
cur->next = pre; //当前节点的next指向它前一个节点
pre = cur; //移动pre指针
cur = temp; //移动当前节点到下一位
}
//循环结束时,cur指向最后一个节点,pre指向倒数第二个节点
cur->next = pre;
return cur;
}
};