反转链表
反转一个单链表。
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
迭代:
/** * 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){ ListNode *p = head->next; ListNode *q = head; while(p != NULL){ q->next = p->next; p->next = head; head = p; p = q->next; } } return head; } };
递归:
/** * 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; } else{ ListNode *p = reverseList(head->next); head->next->next = head; head->next = NULL; return p; } } };