题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL){
return pHead;
}
ListNode* head = new ListNode(-1);
ListNode* pre = head;
ListNode* cur = pHead;
head->next = pHead;
while(cur!=NULL){
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
pHead->next = NULL;
return pre;
}
};
因为下一道题目是翻转部分链表,所以头插法不是很好用,学习了牛客上的解题思路,发现这一种是比较好用的,大致思想就是把cur的next指向pre,然后再向下一个结点迭代。
值得注意的是头结点的去除和尾节点作为头结点返回。
头结点的去除,直接把head的next设置为NULL就好了;尾节点的话,应该就是非空的最后一个节点pre。