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
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种方法:先设置一个虚拟的头节点,防止为空。再交换节点的引用。
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刷题系列]Swap Nodes in Pairs
- [leetcode]Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs、Reverse Nodes in k-Group、Rotate List
- leetcode -- Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- LeetCode_Swap Nodes in Pairs
- LeetCode:Swap Nodes in Pairs
- leetcode 49: Swap Nodes in Pairs
- leetcode之Swap Nodes in Pairs
- LeetCode-Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- leetcode 49: Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs 解题报告
- LeetCode Online Judge 题目C# 练习 - Swap Nodes in Pairs
- 【LeetCode with Python】 Swap Nodes in Pairs
- leetcode 14: Swap Nodes in Pairs
- leetcode—Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs