您的位置:首页 > Web前端 > Node.js

LeetCode——Swap Nodes in Pairs

2014-07-27 11:08 267 查看
Given a linked list, swap every two adjacent nodes and return its head.

For example,

Given 
1->2->3->4
, you should return the list as 
2->1->4->3
.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
原题链接:https://oj.leetcode.com/problems/swap-nodes-in-pairs/
题目:给定一个链表,交换两个邻接节点并返回。

你的算法只能使用常数空间。不能修改表中的值,只有节点自身可以改变。

思路:首先,直接交换两个节点的。可以通过,但是不符合要求。

public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode back = head;
while (back != null) {
if (back.next != null) {
int val = back.val;
back.val = back.next.val;
back.next.val = val;
back = back.next.next;
} else
break;
}
return head;
}

第2种方法:先设置一个虚拟的头节点,防止为空。再交换节点的引用。
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
while (head != null && head.next != null) {
ListNode tmp = head.next.next;
pre.next = head.next;
head.next.next = head;
head.next = tmp;
pre = head;
head = tmp;
}
return dummy.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode