Leetcode 24 Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->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指標的形式來進行倒置
相關文章
- 024,Swap Nodes in PairsAI
- 【leetcode】24. Swap Nodes in Pairs 連結串列奇偶節點交換LeetCodeAI
- 兩種解法搞定Swap Nodes in Pairs演算法題AI演算法
- The best LeetCode NodesLeetCode
- [LeetCode] 336. Palindrome PairsLeetCodeAI
- Leetcode 25 Reverse Nodes in k-GroupLeetCode
- [LeetCode] 2487. Remove Nodes From Linked ListLeetCodeREM
- 【Leetcode】25.Reverse Nodes in k-GroupLeetCode
- [LeetCode] 1497. Check If Array Pairs Are Divisible by kLeetCodeAI
- [Leetcode力扣 25] Reverse Nodes in k-GroupLeetCode力扣
- [LeetCode] 3184. Count Pairs That Form a Complete Day ILeetCodeAIORM
- 【LeetCode】493. Reverse Pairs 翻轉對(Hard)(JAVA)LeetCodeAIJava
- 222. Count Complete Tree Nodes(Leetcode每日一題-2020.11.24)LeetCode每日一題
- leetcode 679. 24 Game(遊戲24點)LeetCodeGAM遊戲
- DAY 24 LeetCode學習筆記LeetCode筆記
- 13-Architecture-nodes
- TWO NODES(HDU-4587)
- 【Lintcode】572. Music PairsAI
- 1512. Number of Good PairsGoAI
- CF1762F Good PairsGoAI
- LeetCode題解(Offer24):反轉連結串列(Python)LeetCodePython
- CF Div. 3 C Beautiful Triple PairsAI
- Vim auto-pairs設定選項AI
- swap擴容
- swap 跟 fstab
- leetcode 24 兩兩交換連結串列中的節點LeetCode
- Solution - Atcoder ABC263G Erasing Prime PairsAI
- E - Remove Pairs(狀壓dp+博弈論)REMAI
- Diff-prime Pairs(思維+素數篩)AI
- IPP SWAP孵化器|IPP SWAP系統開發分析
- Linux Swap擴容Linux
- leetcode 24.兩兩交換連結串列中的節點LeetCode
- LeetCode 24. 兩兩交換連結串列中的節點LeetCode
- linux 修改swap空間Linux
- linux 禁止swap交換Linux
- LINUX 建立swap空間Linux
- oracle RAC dbca的時候報錯提示cluster nodes are not accessibleOracle
- [ARC171C] Swap on Tree