11/4 <LinkedList>

328. Odd Even Linked List

"Go-between"

1. odd odd bit pointer wear

2.even wear even bit pointer

3. evenHead records a node even bit, odd and finally connected evenHead

Note that a case of determining the empty node and the node.

class Solution {
    public ListNode oddEvenList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        
        ListNode odd = head, even = head.next, evenHead = even;
        
        while(even != null && even.next != null){
            odd.next = even.next;
            odd = odd.next;
            even.next = odd.next;
            even = even.next;
        }
        odd.next = EvenHead;
        return head; 
    } 
}

92. Reverse Linked List II

1. For a list of issues, are generally based on past experience to build a dummy node, the first node of the list even Uehara, so even if the head node changes, we can also get a new list by dummy-> next the first node.

Each step will later cur node as node temp, temp purpose of the switching node to the position pre.next. This process needs to maintain nm times.

class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode cur = head;
        
        if(head == null || head.next == null)
            return head;

        for(int i = 1; i < m; i++){
            pre = pre.next;
            cur = pre.next;
        }
          
        
        for(int i = m; i < n; i++){
            ListNode temp = cur.next;
            cur.next = temp.next;
            temp.next = pre.next;
            pre.next = temp;
        }
        return dummy.next;
    }
}

 

 

Guess you like

Origin www.cnblogs.com/Afei-1123/p/11791445.html