Swap Nodes & Reverse Nodes in k-Group
2016-07-05 12:24
381 查看
Swap Nodes |
Given a linked list, swap every two adjacent nodes and return its head.
Example
Given
分析:使用递归,方便又快捷。
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed. Only constant memory is allowed.
Example
Given this linked list:
For k = 2, you should return:
For k = 3, you should return:
Given a linked list, swap every two adjacent nodes and return its head.
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 || head.next == null) return head; ListNode prev = head; ListNode current = head.next; head = current.next; current.next = prev; prev.next = swapPairs(head); return current; } }
Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed. Only constant memory is allowed.
Example
Given this linked list:
1->2->3->4->5
For k = 2, you should return:
2->1->4->3->5
For k = 3, you should return:
3->2->1->4->5
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { /** * @param head a ListNode * @param k an integer * @return a ListNode */ public ListNode reverseKGroup(ListNode head, int k) { if (head == null || size(head) < k) return head; ListNode prev = null; ListNode current = head; ListNode next = null; int i = 1; while (current != null && i <= k) { next = current.next; current.next = prev; prev = current; current = next; i++; } head.next = reverseKGroup(current, k); return prev; } private int size(ListNode head) { int total = 0; while(head != null) { total++; head = head.next; } return total; } }
相关文章推荐
- Node.js实现文件上传
- 24. Swap Nodes in Pairs
- Node的关系型数据库ORM库:bookshelf
- nodejs系列学习:module-----(三)
- nodejs 遍历目录结构
- node.js 上传文件
- hadoop多次格式化后,导致datanode启动不了
- nodejs 的fs 的所有用法
- NodeJS制作爬虫全过程
- NodeJS制作爬虫全过程
- Nodejs爬虫进阶教程之异步并发控制
- Nodejs爬虫进阶教程之异步并发控制
- 基于Node.js的强大爬虫 能直接发布抓取的文章哦
- 基于Node.js的强大爬虫 能直接发布抓取的文章哦
- 【leetcode】25. Reverse Nodes in k-Group
- 【leetcode】24. Swap Nodes in Pairs
- node
- 【leetcode】19. Remove Nth Node From End of List
- Node.js获取AJAX参数Demo
- Node.js实现文件上传