Back to Leetcode Go

24. Swap Nodes in Pairs

website/content/ChapterFour/0001~0099/0024.Swap-Nodes-in-Pairs.md

1.7.11.3 KB
Original Source

24. Swap Nodes in Pairs

题目

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example:


Given 1->2->3->4, you should return the list as 2->1->4->3.

题目大意

两两相邻的元素,翻转链表

解题思路

按照题意做即可。

代码

go

package leetcode

import (
	"github.com/halfrost/leetcode-go/structures"
)

// ListNode define
type ListNode = structures.ListNode

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

func swapPairs(head *ListNode) *ListNode {
	dummy := &ListNode{Next: head}
	for pt := dummy; pt != nil && pt.Next != nil && pt.Next.Next != nil; {
		pt, pt.Next, pt.Next.Next, pt.Next.Next.Next = pt.Next, pt.Next.Next, pt.Next.Next.Next, pt.Next
	}
	return dummy.Next
}




<div style="display: flex;justify-content: space-between;align-items: center;"> <p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0023.Merge-k-Sorted-Lists/">⬅️上一页</a></p> <p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0025.Reverse-Nodes-in-k-Group/">下一页➡️</a></p> </div>