Description
Given a linked list, swap every two adjacent nodes and return its head.
Note
- Your algorithm should use only constant extra space.
- You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example
input: 1->2->3->4
output: 2->1->4->3
解题思路
题目中有说
不能新建一个list然后通过赋值进行虚假的 “ 交换 ” 操作,只能交换内部节点
一直错一直错一直错
Time Limit Exceeded
错误代码长这样
public static ListNode swapPairs(ListNode head) {
ListNode p1 = new ListNode(0);
ListNode p2 = head;
ListNode p = p1;
while(p2 != null && p2.next != null){
p1.next = p2.next.next;
p1 = p1.next;
p1.next = p2.next;
p2 = p2.next.next;
p1 = p1.next;
}
return p.next;
}
放到eclipse里面看了下
一到p2 = p2.next.next
p2就变成了无穷长的list
hmmmmmm想了想换了种插入方式
先对p1、p2进行反序,再接在list后面
这次ok了
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode p = new ListNode(0);
p.next = head;
ListNode t = p;
while (t.next != null && t.next.next != null) {
ListNode a = t.next;
ListNode b = t.next.next;
a.next = b.next;
t.next = b;
t.next.next = a;
t = t.next.next;
}
return p.next;
}
}
顺便附上通过赋值强行 “ 反序 ” 的作弊代码hhhhh
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode p1 = new ListNode(0);
ListNode p2 = head;
ListNode p = p1;
while(p2 != null){
if(p2.next == null)
break;
p1.next = new ListNode(p2.next.val);
p1 = p1.next;
p1.next = new ListNode(p2.val);
p1 = p1.next;
p2 = p2.next;
p2 = p2.next;
}
if(p2 != null)
p1.next = p2;
return p.next;
}
}
其他
- 对指针这种还是理解不透彻
- 说实话到最后都不太理解为什么第一份代码会变成无穷长的list不知道有没有大佬回答一下QuQ