找LeetCode上简单的题目来撑过30天啦(DAY24)

好像有台风要来,天气变得有点冷

题号: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真的有比较熟了,开心


<<:  Composite 合成模式

>>:  口罩脸孔资料集的标注、资料前处理与资料扩增

Day 27 RSpec 的 Mock & Stub

该文章同步发布於:我的部落格 在我一开始学习写 Rails 测试时,会有很常见的问题,就是到底什麽...

AE极光制作2-Day8

接续昨天的练习:https://ithelp.ithome.com.tw/articles/1026...

模型的内容05 def main()

接着我们说明optimizer设定 。 首先,我们先得知道 training and validat...

杂七杂八问题篇

倒数第二篇~ 来个不分类的杂七杂八问题篇, 有些问题,不知道该怎麽分类, 而有些分类,这次没机会写到...

Day 39 (PHP)

1.阵列:一、二、三维 $a[0] = 123; // 一维 $a[1][0] = 10; // 二...