leetcode24,交換鏈表相鄰的節點


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.

 

對於這樣鏈表交換的題目,我一般都有兩種解法。

第一種,看鏈表每個節點帶有的數據量,這道題帶有只有一個value值,只有一個int值,所以我一開始的想法就是,不真實的交換節點,只是交換里面的數據。

這樣的好處是空間復雜度特別省,適合那些每個節點數據很少,要求不高的鏈表交換。

/**
 * 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 || head.next == null)
            return head;
        
        ListNode A = head;
        ListNode B = head.next;
        
        int t;
        while(A != null && B != null){
            t = B.val;
            B.val = A.val;
            A.val = t;
            
            if(B.next == null)
                break;
            A = B.next;
            B = B.next.next;
        }
        
        return head;
    }
}

第二種解法就是真的去交換節點。

那么就需要多余的節點去記錄當前結點的情況然后去交換

我用h,1,2,3這4個節點來說明。

123是原來的節點。

而h是頭節點,指向1

 

下面是交換的步驟。

h->1->2->3

1->3(這個3通過2.next找)

h->2(這個直接有2)

h->->1(這個1也是直接有)

h->3(這個3通過1.next找)

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM