在原地反转,那么就是一边迭代一边跟新每个节点的next指针,把当前节点cur 指向cur->next->next 他的下一个节点指向head,最后跟新一下节点的信息。返回head。因为涉及到了4个 head cur cur->next cur->next->next 所以退出循环的条件是cur->next == null
class Solution { public: /** * @param head: n * @return: The new head of reversed linked list. */ ListNode * reverse(ListNode * head) { // write your code here if (!head || !head->next) return head; if (!head->next->next) { ListNode *cur = head->next; cur ->next = head; head ->next = NULL; return cur; } ListNode *cur = head -> next; ListNode *temp = cur -> next; cur->next = head; head->next = temp; head = cur; cur = head->next;
while (cur->next){ temp = cur->next; cur ->next = cur->next->next; temp->next = head; head = temp; } return head; } };