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

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

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

题目描述

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

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

示例 1:

输入: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

  

原文地址:https://www.cnblogs.com/dul843/p/14257997.html