Last active
November 22, 2018 06:04
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//使用头插入的方式,建立一个新的链表 | |
// 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; | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//使用栈的方式进行逆序 | |
//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