Skip to content

Instantly share code, notes, and snippets.

@qiaoxu123
Last active November 22, 2018 06:04
Show Gist options
  • Save qiaoxu123/758a6f841d0ed5d8228256d6b529c389 to your computer and use it in GitHub Desktop.
Save qiaoxu123/758a6f841d0ed5d8228256d6b529c389 to your computer and use it in GitHub Desktop.
Reverse a singly linked list. ``` Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL ``` Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
//使用头插入的方式,建立一个新的链表
// 12 ms
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *temp = nullptr,*nextNode = nullptr;
while(head){
nextNode = head->next;
head->next = temp;
temp = head;
head = nextNode;
}
return temp;
}
};
//使用栈的方式进行逆序
//4 ms
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head)
return head;
stack<int> nodes;
ListNode *p = head;
ListNode *q = head;
while(p){
nodes.push(p->val);
p = p->next;
}
while(!nodes.empty()){
q->val = nodes.top();
// cout << q->val << " ";
q = q->next;
nodes.pop();
}
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment