给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
题目来源:力扣(LeetCode)
假设,链表为: 1->2->3->4,等价描述为:node(1)->node(2)->node(3)->node(4)。
所以替换过程为:
第1轮:
start: node(1)->node(2)->node(3)->node(4)
temp<-node(1)
pre<-none
nex<-node(2)
cur<-node(1)
cur.next<- next of nex
nex.next<-cur
temp<-cur
temp<- next of temp
end: node(2)->node(1)->node(3)->node(4)
newHead<-nex<-node(2)
pre<-cur<-node(1)
第2轮:
newHead不再赋值
其他以此类推。
最后:
如果没有发生交换,newHead为原来的head。
在上面的描述中,因为原链表的当前节点cur和下一个节点nex交换,所以当前节点的索引cur.next为下一个节点的下一节点 – 索引nex.next,而下一个节点的索引变为当前节点。故此,为了避免操作过程中链表的索引地址混乱,先获取当前位置的下一项,并现保存该索引nex.next。下一次交换时,当前节点cur跳至上次交换开始前的nex.next或者说上次交换完成后的cur.next。这样剩下最后一个问题:上一次交换后的后者的索引指向下一次交换前的前者的索引。那么就需要保存上一次交换后的后者pre,将该索引pre.next重新指向交换后的前者的索引。
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
@author: WowlNAN
@github: https://github.com/WowlNAN
@blog: https://blog.csdn.net/qq_21264377
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
temp=head
newHead=None
pre=None
nex=None
cur=None
while temp!=None and temp.next!=None:
nex=temp.next
cur=temp
cur.next=nex.next
nex.next=cur
if pre!=None:
pre.next=nex
pre=cur
temp=cur
temp=temp.next
if newHead==None:
newHead=nex
if newHead==None:
newHead=head
return newHead