简体   繁体   中英

swap nodes in a linked list overflows java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null|| head.next == null) return head;
        ListNode curr = head;//current node in list we are looking at
        ListNode retList = new ListNode(0);//new linked list to return
        ListNode newHead = retList;//reference to head of the list
        while(curr.next != null); {//while there is another point in the original list
            retList.val = curr.next.val;//the value in the return list = next value in original lis
            retList.next = new ListNode(curr.val);//opposite of last line+creates another node in return list
            if(curr.next.next == null) {//if there is another node after the next one
                curr = curr.next;//if there isnt then the while loop wont go
            }
            else {
                retList.next.next = new ListNode(0);//creates a new node 2 nodes ahead
                retList = retList.next.next;//goes to that node
                curr = curr.next.next;//jumps 2 nodes in the original list
            }
        }
        return newHead;//returns head to the list we are returning
    }
}

I really cant figure out why this doesn't work, the while loop should end. The prompt is to swap ever node in the list with every next node in the list so 1,2,3,4 becomes 2,1,4,3. its here on leetcode https://leetcode.com/problems/swap-nodes-in-pairs/description/ and every time I run my code it just gives me a time exceeded error.

您的解决方案是正确的,但是您的时间已经过去了。

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