问题: 分别用递归和非递归方式来实现反转链表。
思路1: 递归。
java代码:
ListNode reverseList(ListNode head,ListNode newHead){
if(head==null||head.next==null){
newHead=head;
return head;
}
ListNode pre=reverseList(head.next,newHead);
pre.next=head;
head.next=null;
return head;
}
思路2: 非递归。
java代码:
ListNode reverseList(ListNode head){
ListNode dummy=new ListNode(0);
dummy.next=head;
if(head==null)
return head;
ListNode curr=head.next;
head.next=null;
while(curr!=null){
ListNode next=curr.next;
curr.next=dummy.next;
dummy.next=curr;
curr=next;
}
return dummy.next;
}