题目:将单链表反转
分析:可以用迭代或者递归来做
答案:
迭代的示意图:
代码:
/**
* 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* pre = head;
ListNode* cur = head->next;
pre->next = NULL; // the first node turns into the last, so point to null
while (cur){
ListNode* nextp = cur->next;
cur->next = pre;
pre = cur;
cur = nextp;// move to next node
}
return pre;
}
};
16ms
递归:
/**
* 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->next;
ListNode* newHead = reverseList(cur);
cur->next = head;
head->next = NULL;
return newHead;
}
};
8ms。其实就是通过递归把所有节点压栈,直到newhead->next == NULL,找到新的头,然后出栈的时候逆转指针的指向。