题目:
Reverse a singly linked list.
提示:
此题不难,可以用迭代或者递归两种方法求解。记得要把原来的链表头的next置为NULL;
代码:
迭代:
/** * 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) return NULL; ListNode *pre = head, *cur = head->next; pre->next = NULL; ListNode *tmp; while (cur) { tmp = cur->next; cur->next = pre; pre = cur; cur = tmp; } return pre; } };
递归:
/** * 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) { return reverseNode(head, NULL); } ListNode* reverseNode(ListNode* head, ListNode* newHead) { if (!head) return newHead; ListNode *next = head->next; head->next = newHead; return reverseNode(next, head); } };