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

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

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

示例:

给定 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

猜你喜欢

转载自www.cnblogs.com/NPC-assange/p/10741520.html