本文共 1484 字,大约阅读时间需要 4 分钟。
结束条件:head == p
/** * 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) return NULL; ListNode *p = head; while (p->next != NULL) p = p->next; ListNode *q = p->next; ListNode *tempHead = head; while(head != p){ tempHead = head; head = head->next; tempHead->next = q; p->next = tempHead; q = p->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) return NULL; if (head->next == NULL) return head; ListNode *p = head; ListNode *q = p->next; while(q->next != NULL){ p = q; q = q->next; } ListNode *newHead = q; p->next = q->next; q->next = reverseList(head); return newHead; }};
转载地址:http://fjpbb.baihongyu.com/