iT邦幫忙

0

linklist 反轉

各位大大好,這是我的作業,可是做一半有瓶頸,想請教大家
題目:
有個linklist=head,會宣告left和right
left和right中間的數字會反轉
例如:
1->2->3->4->5 left=2, right=4
答案:
1->4->3->2->5
我的程式碼:

/**
 * 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 reverseBetween(ListNode head, int left, int right) {
        ListNode fir=null;
      ListNode cur=head;
        int i=1;
        while(cur!=null){//
            if(left>i){
                 fir=cur;
                cur=cur.next;
               fir.next=cur;
                i++;
                System.out.println(fir.val);
            }
          else{break;}
           
        }
        ListNode next=null;
        ListNode pre=null;
         while(cur!=null){
            if(left<=i && right>=i){
                 next=cur.next;
                cur.next=pre;
                pre=cur;
                cur=next;
                
                i++;
                
            }
         else{break;}
        }
        ListNode tail=null;
          while(cur!=null){
            tail=cur;
              cur=cur.next;
              tail.next=cur;
               
           
        }
        pre.next=tail;
        fir.next=pre;
         
        
        return fir;
    }
}

我跑出來都會變1->4->5
是為什麼呢,謝謝

你好像都沒有使用暫存的變數耶.
amyqaz iT邦新手 4 級 ‧ 2021-09-10 10:01:00 檢舉
一級屠豬士,我再看看要怎麼改
加油!
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
kondic
iT邦新手 5 級 ‧ 2021-09-10 11:31:39
最佳解答

我不是寫java,但C#其實差不多
在接觸這種有節點的題目,我通常都會往遞迴的方向去思考

這是我用C#的寫法


public ListNode reverseBetween(ListNode head, int left, int right)
{
    //目前節點的反轉判斷,若為空值表示終點直接返回
    if (head == null) return head;
    int currentVal = head.val;
    if (currentVal == left) head.val = right;
    if (currentVal == right) head.val = left;
   //下一個節點進行一次反轉方法判斷到終點,再把結果回傳
    head.next = reverseBetween(head.next,left,right);
    return head;
}

amyqaz iT邦新手 4 級 ‧ 2021-09-10 14:24:40 檢舉

謝謝大大

0
海綿寶寶
iT邦大神 1 級 ‧ 2021-09-10 09:07:41

參考這篇

另外我想了解一下
這是幾年級的作業
/images/emoticon/emoticon19.gif

看更多先前的回應...收起先前的回應...
amyqaz iT邦新手 4 級 ‧ 2021-09-10 10:00:06 檢舉

三年級,謝謝海綿寶寶,我再研究看看

國三、高三、大三還是研三
/images/emoticon/emoticon19.gif

amyqaz iT邦新手 4 級 ‧ 2021-09-10 11:03:41 檢舉

大三

了解了,謝謝你的回答

差不多吧,不過我14年前大一念資工,是在玩C /images/emoticon/emoticon01.gif

我要發表回答

立即登入回答