iT邦幫忙

2021 iThome 鐵人賽

DAY 24
0
AI & Data

想到甚麼打甚麼系列 第 24

找LeetCode上簡單的題目來撐過30天啦(DAY24)

  • 分享至 

  • xImage
  •  

好像有颱風要來,天氣變得有點冷

題號:24 標題:Swap Nodes in Pairs 難度:Medium

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Example 1:

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:
Input: head = []
Output: []

Example 3:
Input: head = [1]
Output: [1]

Constraints:
• The number of nodes in the list is in the range [0, 100].
• 0 <= Node.val <= 100

我的程式碼

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null || head.next == null){
            return head;
        }else{
            ListNode f = new ListNode();
            ListNode s = new ListNode();
            ListNode c = new ListNode();
            ListNode temp = new ListNode();
            f = head;
            s = head.next;
            if(head.next==null){
                head =head.next;
                head.next = f;
                return head;
            }
            head = head.next;
            c= head.next;
            //System.out.print("i: "+ c.val+" ");
            int i =1;
            while(s!=null){
                System.out.print(i+": "+ s.val+" ");
                s.next = f;
                temp.next = s;
                if(c!=null){
                    f.next = c;
                    c = c.next;
                    if(c != null){
                        c = c.next;    
                    }
                    
                }else{
                    f.next = null;
                }
                temp = f;
                f = f.next;
                s = s.next;
                
                s = s.next;
                if(s == null){
                    break;
                }
                
                s = s.next;
                
//                 System.out.print(i+": "+ cur.val+" ");
                
//                 System.out.print(i+": "+(cur.next).val +" ");
                
//                 System.out.println(i+": "+(p).val);
            }
        }
        
        return head;
    }
}

邏輯
把前一個指向現在的下一個,現在的指向前一個。

DAY24心得
我覺得我跟LINKLIST真的有比較熟了,開心


上一篇
找LeetCode上簡單的題目來撐過30天啦(DAY23)
下一篇
找LeetCode上簡單的題目來撐過30天啦(DAY25)今天國慶放假啦
系列文
想到甚麼打甚麼30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言