题目:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
示例:
给定1->2->3->4
, 你应该返回2->1->4->3
.
说明:
- 你的算法只能使用常数的额外空间。
- 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
思路:链表和指针在一起就更晕了。。。。直接百度了大神们的代码,先看懂代码。
代码:
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)return head;
ListNode dummy = new ListNode(0); //在头结点之前再放一个节点,注意写法
ListNode l = head.next; //保存交换之后的头结点
dummy.next = head;
while(dummy.next != null && dummy.next.next != null){
ListNode first = dummy.next;
ListNode second = dummy.next.next;
first.next = second.next; //交换的时候使用三个节点交换
second.next = first;
dummy.next = second;
dummy = dummy.next.next;
}
return l;//在这里如果返回head 的话会少了交换后的头结点
}
}
执行时间最短的代码:
还是,嗯。。。。看不懂。。。好绕。。。。
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null) {
return null;
} else if (head.next == null) {
return head;
} else {
ListNode result = head.next;
ListNode tmp = head.next.next;
head.next.next = head;
head.next = swapPairs(tmp);
return result;
}
}
}