LeetCode92 反转链表II
下面介绍三种方法
1.头插法
所谓头插法,就是再反转区间里,每次向后遍历一个结点,就将它插入到,反转区间的头部。
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode;
for(int i = 0;i < left - 1;i++)
pre = pre.next;
ListNode cur = pre.next;
ListNode tmp;
for(int i = 0;i < right - left;i++){
tmp = cur.next;
cur.next = tmp.next;
tmp.next = pre.next;
pre.next = tmp;
}
return dummyNode.next;
}
}
2.穿针引线法
所谓穿针引线法就是先记录反转区间的头、尾结点和他们前后的结点。
然后反转这个区间后,再将他连接上。
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode;
for(int i = 0;i < left - 1;i++)
pre = pre.next;
ListNode rNode = pre;
ListNode lNode = pre.next;
for(int i = 0;i < right - left + 1;i++)
rNode = rNode.next;
ListNode suc = rNode.next;
pre.next = null;
rNode.next = null;
reverseListNode(lNode);
pre.next = rNode;
lNode.next = suc;
return dummyNode.next;
}
ListNode reverseListNode(ListNode head){
ListNode pre = null;
ListNode tmp = null;
ListNode cur = head;
while(cur != null){
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
3.递归
class Solution {
//用于记录边界结点
public ListNode reverseBetween(ListNode head, int left, int right) {
// 递归边界
if (left==1)
return revserList(head,right);
head.next = reverseBetween(head.next, left - 1, right - 1);
return head;
}
//反转链表的前n个结点
//递归解法
public ListNode revserList(ListNode head ,int n){
//记录尾结点位置,避免链表断开
ListNode tail ;
//递归边界
if(n==1)
return head ;
ListNode last=revserList(head.next,n-1);
tail=head.next.next;
head.next.next=head;
head.next=tail;
return last;
}
}