题目:定义一个链表,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
思路:反转链表时,为了保证链表不断开,需要保存三个引用,指向前一结点的引用,当前结点的引用,指向后一结点的引用。
//反转链表
public static ListNode reverseList(ListNode head){
if(head==null)return null;
ListNode reverseHead = null;
ListNode node = head;
ListNode prev = null;
while(node!=null){
ListNode pNext = node.next;
if(pNext==null)
reverseHead = node;
node.next = prev;
prev = node;
node = pNext;
}
return reverseHead;
}
递归写法:
/*
* 递归实现反转链表
*/
public static ListNode reverseListRecursive(ListNode head){
if(head == null || head.next==null) return head;
ListNode newHead = reverseListRecursive(head.next);
//递归返回后继续执行下面的代码
/*
* 假设链表是p0,p1,p2,p3
* 从最后一层返回时newHead=p3;
* 返回到倒数第二次递归:newHead=p3,head=p2,
* head.next=p3,p3.next=p2;p2.next=null;
* 返回到倒数第三次递归:newHead=p3,head=p1,
* head.next=p2,p2.next=p1,p1.next=null;
* 返回到最上面一层:newHead=p3,head=p0,
* head.next=p1,p1.next=p0,p0.next=null
*/
head.next.next = head;
head.next = null;
return newHead;
}
/**
* 递归二
* @param current
* @return
*/
public static ListNode reverse(ListNode current)
{
if (current == null || current.next == null) return current;
ListNode nextNode = current.next;
current.next = null;
ListNode reverseRest = reverse(nextNode);
nextNode.next = current;
return reverseRest;
}
递归返回后继续执行下面的代码