链表系列

206. Reverse Linked List
Easy

Given the head of a singly linked list, reverse the list, and return the reversed list.

 

Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

 

Constraints:

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode front = null;
        ListNode back = head;
        while(back!=null){
            head = back.next;
            back.next=front;
            front=back;
            back=head;
        }
        return front;
    }
}
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = new ListNode(1);
        while(head!=null){
            ListNode t = pre.next;
            pre.next=head;
            head=head.next;
            pre.next.next=t;
        }
        return pre.next;
    }
}

 

 

 
92. Reverse Linked List II
Medium

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]

Example 2:

Input: head = [5], left = 1, right = 1
Output: [5] 

Constraints:

  • The number of nodes in the list is n.
  • 1 <= n <= 500
  • -500 <= Node.val <= 500
  • 1 <= left <= right <= n
/**
 * 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 {
    public ListNode reverseBetween(ListNode head, int l, int r) {
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode leftpre = pre,rightpre=pre;
        //leftpre指向left的前一个
        for(int i=1;i<l;i++)  leftpre=leftpre.next;
        //rightpre指向right当前,记住这里是当前,不是前一个!
        for(int i=1;i<=r;i++) rightpre=rightpre.next;
        //left指向要反转的第一个node
        ListNode left=leftpre.next;
        //right指向第一个不反转的node
        ListNode right = rightpre.next;
        //防止死循环
        rightpre.next=null;
        //反转前的第一个为反转后的最后一个
        ListNode lefttail = left;
        //进行反转,并将反转结果对接leftpre
        leftpre.next = reverse(left);
        //对接反转自后一个与未反转部分
        lefttail.next=right;
        return pre.next;
    }
    //简单的链表反转过程
    public ListNode reverse(ListNode head){
        ListNode pre = new ListNode(0);
        while(head!=null){
            ListNode temp=pre.next;
            pre.next=head;
            head=head.next;
            pre.next.next=temp;
        }
        return pre.next;
    }
}

 

posted @ 2021-11-24 11:46  xiaoyongyong  阅读(34)  评论(0)    收藏  举报