reverse-nodes-in-k-group
来源:互联网 发布:java软件工程师考试 编辑:程序博客网 时间:2024/05/18 01:30
题目描述
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.
For 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
我的代码如下:
import java.util.Scanner;import java.util.Stack;class ListNode{ int val; ListNode next; ListNode(int x){ val=x; next=null; }}public class ReverseNodes { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); String[] a=sc.nextLine().split(" "); int k=sc.nextInt(); int[] b=new int[a.length]; for(int i=0;i<a.length;i++) b[i]=Integer.parseInt(a[i]); ListNode head=createList(b); ListNode headSwaped=reverseKGroup(head,k); while(headSwaped!=null){ System.out.print(headSwaped.val+" "); headSwaped=headSwaped.next; } } static ListNode reverseKGroup(ListNode head,int k){ if(head==null||head.next==null||k<2)return head; ListNode first=new ListNode(0); ListNode pre=first,tail=first,tmp; first.next=head; int count; while(true){ count=k; while(count>0&&tail!=null){ count--; tail=tail.next; } if(tail==null)break; pre.next=tail; pre=head; while(head!=tail){ tmp=head; head=tmp.next; tmp.next=tail.next; tail.next=tmp; } tail=pre; head=pre.next; } return first.next; } static ListNode createList(int[] A){ ListNode head=null; head=new ListNode(A[0]); ListNode node=head; for(int i=1;i<A.length;i++){ node.next=new ListNode(A[i]); node=node.next; } return head; }}
0 0
- Reverse Nodes in k-Group
- Reverse Nodes in K-Group
- Reverse Nodes in k-Group
- Reverse Nodes In K Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- 数据库隔离级别
- freeMark中遍历list集合
- fresco -> FrescoView
- 使用maevn项目的mybatis基础配置及使用
- android 图片加载库 Glide 的使用介绍
- reverse-nodes-in-k-group
- yii 框架
- 【数论】[CQOI2017]小 Q 的表格
- iOS开发 Xcode8中遇到的问题及改动
- JavaScript之Screen对象(BOM)
- 遍历ResultSet结果集的列信息
- 关于mybatis只能查询英文,不能查询中文的问题!!!
- onActivityResult()
- Android对话框使用详解