LeetCode--024--两两交换链表中的节点(java and python)

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

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

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

 

l2       nextStart          l1        l2     nextStart 

1->2->3->4->5->6      2->1->3-4>5->6

 

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode swapPairs(ListNode head) {
11         if(head == null || head.next == null) return head;
12         ListNode dummy = new ListNode(-1);
13         ListNode l1 = dummy;
14         ListNode l2 = head;
15         ListNode nextStart;
16         while(l2 != null && l2.next != null){
17             nextStart = l2.next.next;
18             l1.next = l2.next;
19             l2.next.next = l2;
20             l2.next = nextStart;
21             l1 = l2;
22             l2 = l2.next;
23             
24         }
25         return dummy.next;
26         
27         
28     }
29 }

2019-04-20 16:44:49

 

 1 class Solution:
 2     def swapPairs(self, head: ListNode) -> ListNode:
 3         if head==None or head.next==None:
 4             return head
 5         f=head
 6         s=f.next
 7         head=f.next
 8         while s!=None:
 9             f.next=s.next
10             s.next=f
11             if f.next!=None:
12                 pre=f
13                 f=f.next
14                 s=f.next
15                 if s !=None: #当元素个数不是奇数
16                     pre.next=s
17             else:
18                 break
19         return head

2019-12-03 09:27:52

原文地址:https://www.cnblogs.com/NPC-assange/p/10741520.html