LeetCode 第24题 删除排序数组中的重复项


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

示例:

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

你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
*/

/*/
思路:简单链表置换 为了操作方便,定义三个指针,用于置换
*/


 1 class Solution24 {
 2 
 3   public ListNode swapPairs(ListNode head) {
 4     if (head == null || head.next == null) {
 5       return head;
 6     }
 7     ListNode dummy = new ListNode(0);
 8     dummy.next = head;
 9     ListNode preNode = dummy;
10     while (preNode.next != null && preNode.next.next != null) {
11       ListNode nodeLeft = preNode.next;
12       ListNode nodeRight = preNode.next.next;
13       preNode.next = nodeRight;
14       nodeLeft.next = nodeRight.next;
15       nodeRight.next = nodeLeft;
16       preNode = preNode.next.next;
17     }
18     return dummy.next;
19   }
20 }

猜你喜欢

转载自www.cnblogs.com/rainbow-/p/10311857.html