NOTE

Swap Nodes in Pairs

LeetCode notes on Swap Nodes in Pairs.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Given a linked list, swap every two adjacent nodes and return the head of the modified list. You must solve the problem without modifying node values (only node links may be changed).

2. Approach

Same as Reverse Linked List II

3. Implementation

3.1. Three Pointers

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
    if head == nil || head.Next == nil { return head }
    dummyHead := &ListNode{}
    d := dummyHead
    current := head
    for current != nil {
        var next *ListNode
        d.Next,next = reverse(current, 2)
        d = d.Next.Next
        current = next
    }
    return dummyHead.Next
}

func reverse(head *ListNode, count int) (*ListNode, *ListNode) {
    if head == nil || head.Next == nil {return head, nil}
    var prev *ListNode
    current := head
    var next *ListNode
    for i:=0;i < count;i++ {
        next = current.Next
        current.Next = prev
        prev = current
        current = next
    }
    return prev, current
}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub