題意
Reverse a singly linked list.
click to show more hints.
Subscribe to see which companies asked this question.
解法
將當前元素插入到頭節點之前
實現
/**
* 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 == NULL || head->next == NULL) return head;
ListNode* cur = head;
while(cur->next != NULL){
ListNode* next = cur->next;
cur->next = next->next;
next->next = head;
head = next;
}
return head;
}
};