LeetCode:反转链表
反转链表。
递归反转整个链表。可以使用迭代或递归来实现。
迭代或者递归的代码如下
class Solution {
public ListNode reverseList(ListNode head) {
//迭代
// ListNode cur = null;
// ListNode pre = head;
// while(pre!=null){
// ListNode temp = pre.next;
// pre.next = cur;
// cur = pre;
// pre = temp;
// }
// return cur;
//递归
if(head == null){
return head;
}
if(head.next == null){
return head;
}
ListNode last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}
}
反转链表前n个节点
//后驱节点
ListNode successor = null;
public ListNode reverse(ListNode head ,int right){
if(right == 1){
//记录right+1个节点
successor = head.next;
return head;
}
ListNode last = reverse(head.next,right-1);
head.next.next = head;
//反转的节点和后面的节点连接起来
head.next = successor;
return last;
}
和反转所有链表不同的就是successor需要记录第n+1个节点,反转整个链表直接设置为null即可。
反转链表的一部分
递归
如果left=1,和上一种情况一样,相当于反转前n个元素。如果left!=1,那么将head的索引看作为1的话,就是想从第left个元素开始翻转,如果将head.next索引看作为1的话,就是从第left-1个元素开始翻转。
迭代
定位到要反转的第left-1个结点的位置,前驱结点每次都不会变,改变指针的指向。前面一个空结点是为了避免当left=1时的情况。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
//递归
// //后驱节点
// ListNode successor = null;
// public ListNode reverse(ListNode head ,int right){
// if(right == 1){
// //记录right+1个节点
// successor = head.next;
// return head;
// }
// ListNode last = reverse(head.next,right-1);
// head.next.next = head;
// //反转的节点和后面的节点连接起来
// head.next = successor;
// return last;
// }
// public ListNode reverseBetween(ListNode head, int left, int right) {
// if(left == 1){
// return reverse(head,right);
// }
// head.next = reverseBetween(head.next,left-1,right-1);
// return head;
// }
//迭代
public ListNode reverseBetween(ListNode head, int left, int right){
ListNode dummy = new ListNode(0);
int i=1;
dummy.next = head;
ListNode pre = dummy;
for(;i<left;i++){
pre = pre.next;
}
head = pre.next;
for(i=left;i<right;i++){
ListNode nex = head.next;
head.next = nex.next;
nex.next = pre.next;
pre.next = nex;
}
return dummy.next;
}
}