标签:
解法1:
/** * Definition of ListNode * * class ListNode { * public: * int val; * ListNode *next; * * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param head: The first node of linked list. * @return: The new head of reversed linked list. */ ListNode *reverse(ListNode *head) { // write your code here ListNode* p = head; ListNode* newHead = NULL; while (p){ ListNode* t = p->next; p->next = newHead; newHead = p; p = t; } return newHead; } };
解法2:递归
/** * Definition of ListNode * * class ListNode { * public: * int val; * ListNode *next; * * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param head: The first node of linked list. * @return: The new head of reversed linked list. */ ListNode *reverse(ListNode *head) { // write your code here if (head == NULL || head->next == NULL) return head; ListNode* newHead = reverse(head->next); head->next->next = head; head->next = NULL; return newHead; } };
标签:
原文地址:http://www.cnblogs.com/yxzfscg/p/4782258.html