Reverse a singly linked list.
反转一个链表。
比较常见的方式是迭代。
public static ListNode reverseLinkedList(ListNode head){
ListNode curHead=null;
while(head!=null){
ListNode preHead=curHead;
curHead=head;
head=head.next;
curHead.next=preHead;
}
return curHead;
}
题目中还要求用递归的方式,递归的方式有很多,下面是我写的方式:
private static ListNode preHead=new ListNode(-1);
public static ListNode reverseLinkedList2(ListNode head){
if(head==null)
return head;
helper(head);
return preHead.next;
}
private static ListNode helper(ListNode head){
if(head.next==null){
preHead.next=head;
return head;
}
ListNode tailNode=helper(head.next).next=head;
tailNode.next=null;
return head;
}