反转链表。
例
对于链表 1->2->3
,反向链表是 3->2->1
解题思路:
新建三个指针,CUR指向当前需要反转的节点,预先指向CUR前一个节点(因为当CUR向后移动时会丢失前一个节点的数据),下一个指向CUR后一个节点,如图:
执行一个节点的反转:
然后移动到下一个节点,反转下一个节点:
依次循环操作。
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
}
递归方法:
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}
对于递归算法,最重要的就是明确递归函数的定义。具体来说,我们的 reverse
函数定义是这样的:
输入一个节点 head
,将「以 head
为起点」的链表反转,并返回反转之后的头结点。