[Lintcode]Swap Nodes in Pairs
2016-04-17 09:39
357 查看
Given a linked list, swap every two adjacent nodes and return its head.
Example
Given
should return the list as
简单的实现题。按照描述写代码即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a ListNode
*/
public ListNode swapPairs(ListNode head) {
if(head == null) return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
while(prev.next != null && prev.next.next != null) {
ListNode cur = prev.next;
ListNode tmp = prev.next.next.next;
prev.next = prev.next.next;
prev.next.next = cur;
cur.next = tmp;
prev = prev.next.next;
}
return dummy.next;
}
}
Example
Given
1->2->3->4, you
should return the list as
2->1->4->3.
简单的实现题。按照描述写代码即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a ListNode
*/
public ListNode swapPairs(ListNode head) {
if(head == null) return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
while(prev.next != null && prev.next.next != null) {
ListNode cur = prev.next;
ListNode tmp = prev.next.next.next;
prev.next = prev.next.next;
prev.next.next = cur;
cur.next = tmp;
prev = prev.next.next;
}
return dummy.next;
}
}
相关文章推荐
- LintCode Majority Number iii
- LintCode-最大数
- Subtree
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode --find-the-missing-number(寻找缺失的数)
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- lintcode之最长公共前缀
- lintcode 之 最长公共子串
- 中位数 21% 通过 给定一个未排序的整数数组,找到其中位数。 中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数
- LintCode 翻转二叉树
- LintCode 寻找缺失的数
- LintCode 更新二进制位
- Lintcode 二叉树的后序遍历
- Lintcode 二叉树中序遍历
- Lintcode 二叉树前序遍历
- Lintcode 尾部零的个数
- Lintcode 比较字符串
- Lintcode 主元素