LeetCode--No.24--Swap Nodes In Pairs
2016-06-05 07:08
477 查看
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.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode left = head;
ListNode right = head.next;
ListNode last = right.next;
left.next = last;
right.next = left;
head = right;
ListNode prev = left;
while(last != null && last.next != null){
left = last;
right = last.next;
last = right.next;
prev.next = right;
right.next = left;
left.next = last;
prev = left;
}
return 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.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode left = head;
ListNode right = head.next;
ListNode last = right.next;
left.next = last;
right.next = left;
head = right;
ListNode prev = left;
while(last != null && last.next != null){
left = last;
right = last.next;
last = right.next;
prev.next = right;
right.next = left;
left.next = last;
prev = left;
}
return head;
}
}
相关文章推荐
- [LeetCode]problem 116. Populating Next Right Pointers in Each Node
- windows平台上搭建node.js开发环境
- 237. Delete Node in a Linked Lis
- 文件系统(ext2) inode、block、superblock概念整理
- leetcode-Swap Nodes in Pairs-24
- 给裸接口加一道防护,避免恶意盗刷和爬取
- LeetCode Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- LeetCode Remove Nth Node From End of List
- Hello Node.js
- LeetCode第25题之Reverse Nodes in k-Group
- hadoop1.x NameNode 和SecondNameNode工作原理
- 利用tikz画图时调整node内部文字行距的方法
- Node.js环境搭建和学习(windwos环境)
- LeetCode--No.237--Delete Node In a Linked List
- 深入浅出Node.js(一):什么是Node.js
- 硬连接与软连接,inode与links
- 硬连接与软连接,inode与links
- nodejs+npm+bower安装使用
- nodejs REPL清屏