您的位置:首页 > Web前端 > Node.js

reverse-nodes-in-k-group

2017-04-11 10:33 288 查看
题目描述

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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: