/**
* 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/上 每次我运行我的代码时,它只会给我一个超出时间的错误。
答案 0 :(得分:0)
你的解决方案是正确的,但你的时间结束了。