Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

交換鏈表相鄰節點的值。

解題思路:每兩個節點的交換過程分成三步:先把輔助節點的指針指向第二個節點,然後第一個節點的指針指向第三個節點

最後第二個節點的指針指向第一個節點



/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
       if (head == null ) {	//如果鏈表爲空,返回空
    		return null;
		}
    	if (head.next == null) {//如果鏈表有一個節點,則返回頭節點
			return head;
		}
    	
		ListNode dummy = new ListNode(0);//創建輔助節點
		dummy.next = head;
        ListNode first = dummy;
        ListNode cur = head;
        
        while (cur != null && cur.next != null) {
            //節點間的next值交換
			first.next = cur.next;
			cur.next = cur.next.next;
			first.next.next = cur;
			//重新設置新的開始位置
			first = cur;
			cur = cur.next;
		}
        //返回鏈表的頭節點
        return dummy.next;
    }
}


發佈了97 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章