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
我的代码如下:
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; } }
相关文章推荐
- Reverse Nodes in k-Group
- ( Leetcode 25 ) Reverse Nodes in k-Group
- LeetCode25 Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- [Leetcode] Reverse Nodes in k-Group (Java)
- Reverse Nodes in k-Group
- LEETCODE: Reverse Nodes in k-Group
- LeetCode Reverse Nodes in k-Group
- LeetCode Reverse Nodes in k-Group
- leetcode — reverse-nodes-in-k-group
- Reverse Nodes in k-Group -- leetcode
- [LeetCode] Reverse Nodes in k-Group
- LeetCode (25) Reverse Nodes in k-Group (链表)
- leetcode-25-Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- leetcode 42: Reverse Nodes in k-Group
- Leetcode Reverse Nodes in k-Group
- LeetCode(25)Reverse Nodes in k-Group
- 【leetcode】Reverse Nodes in k-Group
- [leetcode]Reverse Nodes in k-Group @ Python