24.两两交换链表中的节点

题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/

题目描述

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

 

刷题-Leetcode-24.两两交换链表中的节点

 

输入:head = [1,2,3,4]
输出:[2,1,4,3]

示例 2:

输入:head = []
输出:[]

示例 3:

输入:head = [1]
输出:[1]

提示:

  • 链表中节点的数目在范围 [0, 100] 内
  • 0 <= Node.val <= 100

 

题目分析

迭代法

  边界条件总是忘记,要注意任何时候都要有返回值。

  要注意或的短路情况 or前后不可颠倒顺序

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, val=0, next=None):
 4 #         self.val = val
 5 #         self.next = next
 6 class Solution:
 7     def swapPairs(self, head: ListNode) -> ListNode:
 8         #Iteration
 9         res = ListNode()
10         res.next = head;
11         cur = res;
12 
13         while(cur.next!=None and cur.next.next!=None):
14             next = head.next;
15             tmp = next.next;
16 
17             cur.next = next;
18             head.next = tmp;
19             next.next = head;
20 
21             cur = head;
22             head = head.next;
23         return res.next
24 
25         if(head.next==None or head==None):
26             return head

 

  

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-27
  • 2022-12-23
  • 2022-01-13
  • 2021-12-03
  • 2021-11-11
  • 2021-07-30
猜你喜欢
  • 2021-07-19
  • 2021-10-03
  • 2022-01-13
  • 2021-06-29
  • 2021-08-24
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案