Skip to content

Latest commit

 

History

History
93 lines (76 loc) · 1.75 KB

24.两两交换链表中的节点.md

File metadata and controls

93 lines (76 loc) · 1.75 KB

24. 两两交换链表中的节点

url

题目

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

输入:head = [1,2,3,4]
输出:[2,1,4,3]
输入:head = []
输出:[]
输入:head = [1]
输出:[1]

方法

code

js

let swapPairs = head => {
    if (head === null)
        return head;
    let node = new ListNode();
    node.next = head;
    let pre = node;
    while (pre.next !== null && pre.next.next !== null) {
        let l1 = pre.next, l2 = pre.next.next;
        let next = l2.next;
        l1.next = next;
        l2.next = l1;
        pre.next = l2;
        pre = l1;
    }
    return node.next;
};

go

func swapPairs(head *ListNode) *ListNode {
	if head == nil {
		 return head
	}
	node := &ListNode{Val: 0}
	node.Next = head
	pre := node
	for pre.Next != nil && pre.Next.Next != nil {
		l1, l2 := pre.Next, pre.Next.Next
		next := l2.Next
		l1.Next = next
		l2.Next = l1
		pre.Next = l2
		pre = l1
	}
	return node.Next
}

java

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null)
            return head;
        ListNode node = new ListNode(0);
        node.next = head;
        ListNode pre = node;
        while (pre.next != null && pre.next.next != null) {
            ListNode l1 = pre.next, l2 = pre.next.next;
            ListNode next = l2.next;
            l1.next = next;
            l2.next = l1;
            pre.next = l2;
            pre = l1;
        }
        return node.next;
    }
}