24 Swap Nodes in Pairs

交换链表相邻节点值。涉及到这种交换节点的问题,可以

先修改两个前驱节点的next指针,再修改当前节点的next指针。

Python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None:
            return head
        dummy = ListNode(0)
        dummy.next = head
        prev, node1 = dummy, head
        while node1 and node1.next:
            # current node => node
            # current second node => node.next
            prev.next = node1.next
            node1.next = node1.next.next
            node1.next.next = node1
            prev = node1
            node1 = node1.next
        return dummy.next

Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null){
            return null;
        }
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode prev = dummyHead;
        ListNode node1 = head;
        ListNode node2 = null;
        while( node1 != null && node1.next != null){
            node2 = node1.next;
            //modify two previous
            prev.next = node2;
            node1.next = node2.next;
            //modify two nodes' relationship
            node2.next = node1;
            // go on
            prev = node1;
            node1 = node1.next;
        }
        return dummyHead.next;
    }
}

results matching ""

    No results matching ""