反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
代码1:
//2020_04_21
//双指针
//null 5 -> 4 -> 3 -> 2 -> 1 -> null
// cur pre
//null <- 5 -> 4 -> 3 -> 2 -> 1 -> null
// cur pre
//...
//null <- 5 <- 4 <- 3 <- 2 <- 1 null
// cur pre
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseList(ListNode *head)
{
ListNode *cur = NULL;
ListNode *pre = head;
ListNode *t;
while(pre){
t = pre->next;
pre->next = cur;
cur = pre;
pre = t;
}
return cur;
}
};
代码2:
//2020_04_21
//栈
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return NULL;//head为空
ListNode* res, *t;
stack <int> s;
while(head){//依次压栈
s.push(head -> val);
head = head -> next;
}
res = new ListNode(s.top());//由于没有头节点,先取出第一个
s.pop();
t = res;
while(!s.empty()){//依次取出
t -> next = new ListNode(s.top());
t = t -> next;
s.pop();
}
return res;//返回结果
}
};
结果:
原文:https://www.cnblogs.com/iceix/p/12743896.html