iT邦幫忙

0

java linklist 問題

大家好:
想請教,我希望我的linklist有二倍的長度
例如:head= 1->2->3
我希望我可以 ListNode myans=1->2->3->1->2->3
可是我的寫法卻一直錯誤.....
請各位幫我一下,謝謝

/**
 * 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 test(ListNode head) {
        ListNode tmp=head;
        
        tmp=head;
        ListNode ans=new ListNode(0);
        ListNode cur=ans;
         for(int i=0;i<2;i++){//用for讓他跑2次不行嗎??
                tmp=head;
              while(tmp!=null){
                 cur.next=tmp;
                 tmp=tmp.next;
                  cur=cur.next;
                  
             }
       }
           
        return ans;
    }
}
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
喵凹咿唉思嗯
iT邦研究生 5 級 ‧ 2021-10-27 15:55:17
最佳解答

在複製節點的過程應該會需要new新的物件出來才對, 要理解為什麼錯, 可以拿紙筆畫圖看看, 可能會比較好理解哪邊有問題

    public ListNode test(ListNode head) {
        ListNode ans=new ListNode();
        ListNode cur=ans;
        for(int i=0;i<2;i++){//用for讓他跑2次不行嗎??
            ListNode tmp = head;
            while(tmp!=null){
                cur.next = new ListNode(tmp.val, null);
                cur = cur.next;
                tmp=tmp.next;
            }
        }
        return ans.next;
    }
amyqaz iT邦新手 4 級 ‧ 2021-10-27 16:56:59 檢舉

喵凹咿唉思嗯,了解了,我有解出來了,謝謝

1
Luke
iT邦研究生 5 級 ‧ 2021-10-27 10:55:46

參考看看吧

class Solution {
    public ListNode test(ListNode head ,int iii = 0) {
        if(null == head)
           return head;
        ListNode ans=new ListNode(0);
        head.next = ans;
        if(iii == 0)
            test(ans,1);
        return head;
    }
}
amyqaz iT邦新手 4 級 ‧ 2021-10-27 11:32:51 檢舉

Luke大大好:
我試過您的程式碼,不行耶..

我要發表回答

立即登入回答