简体   繁体   中英

infinite loop, LeetCode 1721

here's my code:

class Solution {
    public int size (ListNode head)
    {
        int size = 0;
        ListNode curr = head;
        while (curr != null)
        {
            size ++;
            curr = curr.next;
        }
        return size;
    }
    public ListNode swapNodes(ListNode head, int k) {
        ListNode curr = head;
        ListNode curr2 = head;
        ListNode pre = null;
        ListNode pre2 = null;
        ListNode result = head;
        for (int i = 1; i < k && curr != null; i ++)
        {
            pre = curr;
            curr = curr.next;
        }
        int size = size(head);
        for (int i = 0; i < (size - k) && curr2 != null; i ++)
        {
            pre2 = curr2;
            curr2 = curr2.next;
        }
        ListNode tmp = curr.next;
        ListNode tmp2 = curr2.next;
        pre.next = curr2;
        curr2.next = tmp;
        pre2.next = curr;
        curr.next = tmp2;
        return head;
        
    }
}

there seems to be an infinite loop in one of the cases and i can't fix it, can someone help please?

for me everything works fine. Maybe you are using other inputs or initialising the List in a wrong way.

I added a method to your ListNode class to create the list in a fluent way:

public ListNode addListNode(int v) {
    ListNode listNode = new ListNode(v);
    next = listNode;
    return listNode;
}

and a print Method to your Solution class to print the list.

public static void printList(ListNode head)
{
    StringBuilder out = new StringBuilder();
    ListNode curr = head;
    while (curr != null)
    {
        out.append(curr.val).append(",");
        curr = curr.next;
    }
    System.out.println(out);
}

Running it with this main method:

public static void main(String[] args) {
    ListNode listNode = new ListNode(1);
    ListNode currNode = listNode.addListNode(2);
    for( int i = 3; i <= 10; i++) {
        currNode = currNode.addListNode(i);
    }
    // you also could write listNode.addListNode(2).addListNode(3).addListNode(4) ...

    printList(listNode);
    System.out.println("SwapNodes");
    ListNode swappedListNode = swapNodes(listNode, 2);
    printList(swappedListNode);
}

it outputs

1,2,3,4,5,6,7,8,9,10,
SwapNodes
1,9,3,4,5,6,7,8,2,10,

So it seems to work as expected, no infinite loop. As I mentioned at the beginning feel free to add your main method and the way you are calling the swapNodes Method.

You can edit your question and add these informations..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM