Swap Nodes in Pairs
2016-07-23 06:16
495 查看
/** * 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) { ListNode dummy = new ListNode(0); ListNode prev = dummy; ListNode node = head; dummy.next = node; int count = 0; while (node != null) { ListNode next = node.next; count++; if (count == 2) { prev = helper(prev, next); count = 0; } node = next; } return dummy.next; } private ListNode helper(ListNode prev, ListNode next) { ListNode last = prev.next; ListNode cur = last.next; while (cur != next) { last.next = cur.next; cur.next = prev.next; prev.next = cur; cur = last.next; } return last; } // public ListNode swapPairs(ListNode head) { // ListNode dummy = new ListNode(0); // ListNode prev = dummy; // dummy.next = head; // while (head != null && head.next != null) { // ListNode next = head.next.next; // prev.next = head.next; // head.next.next = head; // prev = head; // head.next = next; // head = next; // } // return dummy.next; // } }
相关文章推荐
- NodeMCU多串口通信(轮询)
- Node.js实现单页面爬虫
- node.js 获得月份
- 几个常用的Node方法
- NodeMCU之旅(一):构建、刷入固件,上传代码
- node V4.47版本,傻瓜式安装!(终于让俺装上了)
- GDataXMLNode使用
- leetcode 24.Swap Nodes in Pairs
- leetcode 24.Swap Nodes in Pairs
- Datanode概述
- 安装node.js
- DAY9:leetcode #19 Remove Nth Node From End of List
- DataNode工作原理(四)
- NameNode元数据的管理机制(三)
- nodejs--process
- How To Work With JSON In Node.js / JavaScript
- Node.js:常用工具util
- JavaScript之firstChild属性、lastChild属性、nodeValue属性学习
- mac使用homebrew手动管理node版本
- node.js 使用createServer创建最基础的node应用。