NowCoder《剑指offer》24--反转链表https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目描述
输入一个链表,反转链表后,输出新链表的表头。
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
解题思路
1 用栈
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL || pHead -> next == NULL) return pHead;
ListNode* p = pHead;
stack<ListNode* > s;
while(p -> next) {
s.push(p);
p = p -> next;
}
ListNode* head = p;
while(!s.empty()) {
p -> next = s.top();
p = p -> next;
s.pop();
}
p -> next = NULL;
return head;
}
};
2 新建链表
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL || pHead -> next == NULL) return pHead;
ListNode *reHead = NULL, *cur = pHead, *tmp = NULL,*pre = NULL;
while(cur != NULL) {
tmp = cur->next;
cur->next = pre;
if(tmp == NULL) reHead = cur;
pre = cur;
cur = tmp;
}
return reHead;
}
};
3 头结点插入法
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL || pHead -> next == NULL) return pHead;
ListNode *dummy = new ListNode(-1);
ListNode *pCur = pHead, *pNex;
while(pCur != NULL) {
pNex = pCur->next;
pCur->next = dummy->next;
dummy->next = pCur;
pCur = pNex;
}
return dummy->next;
}
};
4 就地反转
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL || pHead -> next == NULL) return pHead;
ListNode *dummy = new ListNode(-1);
dummy->next = pHead;
ListNode *prev = dummy->next;
ListNode *pCur = prev->next;
while(pCur != NULL) {
prev->next = pCur->next;
pCur->next = dummy->next;
dummy->next = pCur;
pCur = prev->next;
}
return dummy->next;
}
};
5 递归:leetcode 206 答案
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL || head->next==NULL) return head;
ListNode *n = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return n;
}
};;
参考文献
[1] LeetCode 206.反转链表4种方法图解(①就地反转②头插法③迭代法④递归法)Java语言_棒棒的小笨笨的博客-CSDN博客