Reprint please indicate the source http://www.cnblogs.com/haozhengfei/p/9e6f4dda3138cf9fab17f996ec85b624.html
the K reverse order problem in the list
List of K reverse orderThe 7th section of the list of K reverse order exercises
There is a single linked list, please design an algorithm, so that each k nodes in reverse order, if the last not enough K nodes a group, then not adjust the last few nodes. For example the list 1->2->3->4->5->6->7->8->null,k=3 this example. After adjustment for, 3->2->1->6->5->4->7->8->null. Because of k==3, the reverse is reversed between each of the three nodes, but the 7,8 is not adjusted because only two nodes are not enough.
Given the head of a single-linked list, given the K value, returns the head pointer of the linked list after the reverse order.
Java (javac 1.7)Code Auto-Complete1
Import Java. util. *;
2
3
/*
4
public class ListNode {
5
int Val;
6
ListNode next = null;
7
8
ListNode (int val) {
9
This.val = val;
10
}
11
}*/
12
Public class Kinverse {
13
Public ListNode Inverse (listnodeheadintk) {
14
if (k<2) {
15
return head;
16
}
17
ListNode cur = head; //The current node being traversed
18
ListNode Start = null;
19
ListNode Pre = null;
20
ListNode Next = null; //Next node to traverse
21st
int Count = 1;
22
while (cur!=null) {
23
Next = cur. next;
24
if (count= =k) {//count meet requirements start reverse order
25
Start = Pre == NULL ? Head pre. next;
26
Head = Pre == NULL ? cur head;
27
resign (prestartcurnext);
28
Pre = start;
29
Count = 0;
30
}
31
Count ++;
32
cur = next;
33
}
34
return head;
35
}
36
Public void resign (listnodeleftlistnodestartlistnodeEnd,
37
ListNode Right {
38
ListNode Pre = start;
39
ListNode cur = start. next;
40
ListNode Next = null;
41
while (cur!=right) {
42
Next = cur. next;
43
cur. Next = pre;
44
Pre = cur;
45
cur = next;
46
}
47
if (left!=null) {
48
left. Next = End;
49
}
50
start. Next = right;
51
}
52
}
Your code is saved
The answer is right: Congratulations! The program you submitted passed all of the test casesRun
Algorithm--The K-order problem of linked list