Reverse a singly linked list.
1.顺序反转:O(n) time,O(1)space
/**
* 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* pre = NULL;
ListNode* next = NULL;
ListNode* current = head;
while(current!=NULL){//iteratively
next = current->next;
current->next = pre;
pre = current;
current = next;
}
return pre;
}
};
2.利用栈反转,顺序遍历,再用栈反向输出,组成新的链表。O(n) time,O(n) space
3. 递归可能导致函数的层级很深
此题与剑指offer 面试题16 以及面试题5 类似