Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note: Your algorithm should use only constant extra space.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
题目要求对链表中的节点进行交换,从左向右每次交换一对,并且不能修改节点的值(value),所以我们只能通过修改节点的Next指针来实现交换。
我们知道,对链表中的节点进行交换会涉及到4个节点,即cur(当前节点),pre(当前节点前面的节点),post(当前节点后面的节点),post2(post节点后面的节点)。只要有了这四个节点的指针,那么我们就能够直接对cur节点和post节点进行交换,同时保证链表不会断。做法如下:
cur.Next, post.Next = post2, cur
pre.Next = post
因此只要我们能够不断迭代更新cur,pre,post,post2的值,那么就能够通过遍历链表直接完成所有需要交换的节点的交换。
算法实现如下:
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */
func swapPairs(head *ListNode) *ListNode {
// 链表长度为0或1时可以直接返回
if head == nil || head.Next == nil {
return head
}
// 初始化
var pre, cur, post, post2 *ListNode
cur = head
post = cur.Next
post2 = post.Next
result := post
for ; cur != nil && post != nil ; {
// 交换cur节点和post节点
cur.Next, post.Next = post2, cur
if pre != nil {
pre.Next = post
}
//更新cur,pre,post,post2
pre = cur
cur = cur.Next
if cur != nil {
post = cur.Next
} else {
post =nil
}
if post != nil {
post2 = post.Next
} else {
post2 = nil
}
}
return result
}