/* wrong
if (head == NULL)
return head;
if (head->next == NULL)
return head;
ListNode*prev = head;
ListNode*cur = head->next;
ListNode*tail = head;
while (cur->next!=NULL)
{
tail->next = cur->next;
cur->next = prev;
prev = cur;
cur = cur->next;
}
tail->next = cur->next;
cur->next = prev;
head = cur;
return head;*/
/*right
if (head == NULL || head->next == NULL)
return head;
ListNode*prev = head;
ListNode*cur = head->next;
ListNode*tail = cur->next;
while (cur->next!=NULL)
{
#if 0
cur->next = head;
prev->next = tail;
head = cur;
cur = cur->next;//这样不行,由于cur->next已经指向head,所以cur = cur->next找不到下一个正确的位置,所以记录tail是cur->next的位置,用cur=tail
tail = cur->next;
prev->next = tail;
cur->next = head;
head = cur;
cur = tail;
tail = cur->next;
}
cur->next = head;
prev->next = tail;
head=cur;
return head;*/
ListNode *prev=NULL;
ListNode*curr=head;
while(curr!=NULL)
{
ListNode *nextTmp=curr->next;
curr->next=prev;
prev=curr;
curr=nextTmp;
}
return prev;
//这个算法简洁,比我写的简单多了
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
递归我看了好久啊啊啊啊啊啊,这是我的理解,假设链表是[1, 2, 3, 4, 5]从最底层最后一个reverseList(5)来看
返回了5这个节点
reverseList(4)中
p为5
head.next.next = head 相当于 5 -> 4
现在节点情况为 4 -> 5 -> 4
head.next = null,切断4 -> 5 这一条,现在只有 5 -> 4
返回(return)p为5,5 -> 4
返回上一层reverseList(3)
处理完后返回的是4 -> 3
依次向上