Leetcode 24 Swap Nodes in Pairs

HowieLee59發表於2018-10-20

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

Example:

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

Note:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list's nodes, only nodes itself may be changed.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode list = head;
        ListNode node = new ListNode(0);
        ListNode n = node;
        if(head == null){
            return list;
        }
        Stack<Integer> stack = new Stack<>();
        while(list != null){
            stack.add(list.val);
            list = list.next;
            if(stack.size() == 2){
                while(!stack.isEmpty()){
                    node.next = new ListNode(stack.pop());
                    node = node.next;
                }
            }
        }
        if(!stack.isEmpty()){
            node.next = new ListNode(stack.pop());
        }
        return n.next;
    }
}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode newHead = new ListNode(0);
        newHead.next = head;
        head = newHead;
        while(head.next!=null){
            ListNode temp = head.next;
            if(temp.next==null) break;
            head.next = temp.next;
            temp.next = temp.next.next;
            head.next.next = temp;
            head = head.next.next;
            
        }
        return newHead.next;
    }
}

 

上面的是使用的stack進行儲存,每次儲存結束後利用棧的後進先出來倒序;下面的程式碼為直接進行連結串列的操作,主要是操作next指標的形式來進行倒置

相關文章