/**
* 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
}
}
我真的不知道为什么这不起作用,while循环应该结束。提示是将列表中的每个节点与列表中的每个下一个节点交换
1,2,3,4变成2,1,4,3。它在leetcode https://leetcode.com/problems/swap-nodes-in-pairs/description/上
每次我运行代码时,都会给我一个超时错误。
最佳答案
您的解决方案是正确的,但是您的时间已经过去了。
关于java - 链表中的交换节点溢出Java,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49838715/