程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Daily question python87: exchange nodes in the linked list in pairs

編輯:Python

subject : I'll give you a list , Two or two exchange the adjacent nodes , And return the head node of the linked list after exchange . You must complete this problem without modifying the value inside the node ( namely , Only node switching can be performed ).

Example 1:

Input :head = [1,2,3,4] Output :[2,1,4,3]
Example 2:

Input :head = [] Output :[]
Example 3:

Input :head = [1] Output :[1]

Tips :

The number of nodes in the linked list is in the range [0, 100] Inside 0 <= Node.val <= 100

Program description : If dummy nodes are not used , The code is like the following error code , If the linked list is disconnected ( According to the code drawing )

All the code :
Correct code :

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
p = ListNode(0)
p.next = head
cur = p
while cur.next and cur.next.next:
node1 = cur.next
node2 = cur.next.next
cur.next = node2
node1.next = node2.next
node2.next = node1
cur = node1
return p.next

Error code :

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
p = head
cur = head.next
q = cur.next
while cur.next:
p.next = q
cur.next = p
p = q
cur = p.next
q = cur.next
cur.next = p
return head

Title source : Power button (leetcode)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved