题目描述
输入一个链表,反转链表后,输出新链表的表头。
栈:
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null)return head;
ListNode pre=head,now=head.next;
while(now!=null){
pre.next=now.next;
now.next=head;
head=now;
now=pre.next;
}
return head;
}
}
递归:
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null)return head;
ListNode h=ReverseList(head.next);
head.next.next=head;
head.next=null;
return h;
}
}
递归解释:
作为递归函数参数的节点指针,在其为空指针或者其next为空指针的时候递归终止。然后很明显,最后一次递归return的是链表最后一个节点指针,pReverseNode作为此节点指针的copy,返回给上一个递归函数,如此循环,最后返回给初始函数,作为新链表的头指针。
从倒数第二个递归开始执行后面的语句:pHead->next->next=pHead; pHead->next=NULL;pHead是递归函数的参数,是当前要处理的节点,对应链表的倒数第二个节点指针,pHead->next是最后一个节点的指针,命名为lastNode,可以这样看:(lastNode)->next = pHead,pHead->next = NULL。之后节点指针依次出栈,每次修改当前节点的下一个节点指向自己,然后自己指向空指针,,,一直到当前节点为firstNode,(firstNode->next)->next = firstNode, firstNode->next = null。