leetcode-反转链表(递归实现)
基本思路
实现方式有递归和非递归,非递归的简单些,递归的难些。
非递归的思路就是设置个新的前置节点,然后依次将前置节点的下一个节点后移,例如当前链表是ABC,设置个前置节点N,此时为NABC,依次移动为NBAC,NCBA。
递归的思路则是假如当前是ABC,设置前置节点N,此时为NABC,每次递归将最后一个移动到前置节点之前,即NCAB,NCBA。第一次递归传入的节点为N,第二次为C,以此类推。
代码实现
递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
//递归写法
public ListNode reverseList(ListNode head) {
ListNode index = new ListNode(-1);
index.next = head;
reverse(index);
return index.next;
}
public void reverse(ListNode head){
if(head.next == null || head.next.next == null) return;
ListNode last = head,pre_last=head,temp=null;
while(last.next != null){
pre_last = last;
last = last.next;
}
temp = head.next;
pre_last.next = null;
last.next = head.next;
head.next = last;
reverse(last);
}
}
非递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode new_head = new ListNode(-1),index = new_head;
new_head.next = head;
ListNode cur = new_head.next;
while(cur != null && cur.next != null){
ListNode temp = cur.next;
cur.next = temp.next;
temp.next = index.next;
index.next = temp;
}
return index.next;
}
}