Swap Nodes in Pairs
2017-05-22 22:14
281 查看
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.
代码如下:
public class SwapNodesInPairs {
//accepted
public ListNode swapPairs(ListNode head){
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;
while(current.next != null && current.next.next !=null){
ListNode first = current.next;
ListNode second = current.next.next;
first.next = second.next;
current.next = second;
current.next.next = first;
current = current.next.next;
}
return dummy.next;
}
}
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.
代码如下:
public class SwapNodesInPairs {
//accepted
public ListNode swapPairs(ListNode head){
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;
while(current.next != null && current.next.next !=null){
ListNode first = current.next;
ListNode second = current.next.next;
first.next = second.next;
current.next = second;
current.next.next = first;
current = current.next.next;
}
return dummy.next;
}
}
相关文章推荐
- [LeetCode]24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- leetcode 之Swap Nodes in Pairs(21)
- Leetcode 24 Swap Nodes in Pairs
- LeetCode(24)Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- LeetCode Swap Nodes in Pairs
- Leetcode_24_Swap Nodes in Pairs
- LinkedList-24-Swap Nodes in Pairs
- Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- leetcode-Swap Nodes in Pairs-24
- Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- LeetCode Swap Nodes in Pairs
- leetcode解题方案--024--Swap Nodes in Pairs
- LeetCode_Linked List_Swap Nodes in Pairs
- Swap Nodes in Pairs