Leetcode206:给一个单链表的头结点head,请你反转链表,并返回反转后的链表。
两种方法,带头节点和不带头节点。
1.建立虚拟头结点辅助反转
前面分析链表插入元素的时候,会发现如何处理头结点是个麻烦的问题,为此可以先建立一个虚拟的节点ans,并且令ans.next = head,这样可以很好的简化我们的操作。
如下图所示,如果我们将{1->2->3->4->5}进行反转,我们首先建立一个虚拟节点ans,并令ans.next=node(1),接下来我们每次从旧的链表拆下来一个节点接到ans后面,然后将其他线调整好就行了。
public static ListNode reverseList(ListNode head){
ListNode ans = new ListNode(-1);
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = ans.next;
ans.next = cur;
cur = next;
}
return ans.next;
}
2.直接操作链表实现反转
不借助虚拟节点的方式更难,面试考察。
执行过程示意图:
cur表示指向旧链表的首节点,prev表示已经调整好的新链表的首节点,next表示下一个要调整的节点。
public ListNode reverseList(ListNode head){
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
3.拓展:通过递归来实现反转。
public ListNode reverseList(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}