分類:LinkedList
考察知識(shí)點(diǎn):LinkedList
最優(yōu)解時(shí)間復(fù)雜度:**O(n) **
24. Swap Nodes in Pairs
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.
代碼:
我的解法:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None or head.next==None:
return head
dummy=ListNode(0)
dummy.next=head
l1=dummy
l2=head
while(l2!=None and l2.next!=None):
new_head=l2.next.next
l1.next=l2.next
l2.next.next=l2
l2.next=new_head
l1=l2
l2=l2.next
return dummy.next
討論:
1.這道題在面試中出現(xiàn)頻率挺低的
2.這道題主要就是為了讓人搞明白鏈表的next到底是啥,會(huì)不會(huì)被繞暈(事實(shí)上我就覺得非常的暈,暈上天了@.@)

過程圖

Outcome