版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Neo233/article/details/83239759
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
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
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list's nodes, only nodes itself may be changed.
1)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
//一定要注意好节点的next指针的指向
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode node = new ListNode(0);
ListNode list = head;
ListNode n = node;//标记下节点,直接返回
Stack<Integer> stack1 = new Stack<>();//当剩余的还大于K的时候
Stack<Integer> stack2 = new Stack<>();//当最后的个数不到k个的时候
while(list != null){
while(stack1.size() < k && list != null){
stack1.push(list.val);
list = list.next;
}//首先压入栈
if(stack1.size() == k){
while(!stack1.isEmpty()){
node.next = new ListNode(stack1.pop());
node = node.next;
}
}else if(stack1.size() < k){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
while(!stack2.isEmpty()){
node.next = new ListNode(stack2.pop());
node = node.next;
}
}
}
return n.next;
}
}
2)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
//top1的解法总是这么强(膜拜)
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode p = head;
int i = 0;
while(p != null && i < k) {
p = p.next;
i++;
}
if(i == k) {
p = reverseKGroup(p, k);
while(i-- > 0) {
ListNode tmp = head.next;
head.next = p;
p = head;
head = tmp;
}
head = p;
}
return head;
}
}