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
similar like the question Reverse LinkList II
c++
ListNode *reverseKGroup(ListNode *head, int k) {
if(!head) return NULL;
ListNode *p = new ListNode(0);//safe guard
p->next = head;
head = p;
ListNode *q = p;
while(true){
int i=0;
while(q && i<k){q = q->next; i++;}
if(!q) return head->next;
else{
while(p->next!=q){
ListNode *r = q->next;
ListNode *l = p->next;
q->next = p->next;
p->next = l->next;
l->next = r;
}
for(int j=0; j<k;j++)
p=p->next;
q=p;
}
}
return head->next;
}Java
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || head.next == null) return head;
ListNode p = head;
int len = 0;
while(p!=null){
len++;
p = p.next;
}
if(len<k) return head;
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode l1 = newHead;
ListNode pre = head;
int num = len/k;
while(num>0){
int dis = k;
ListNode post = pre.next;
while(dis>1){
ListNode temp = post.next;
post.next = pre;
pre = post;
post = temp;
dis--;
}
l1.next.next = post;
ListNode p1 = l1.next;
l1.next = pre;
l1 = p1;
pre = post;
num--;
}
return newHead.next;
}

本文介绍了一种算法,该算法将链表中的节点每K个一组进行反转,并返回修改后的链表。讨论了当节点数不是K的倍数时剩余节点保持原状的情况,同时强调了仅允许使用常量内存进行操作。
216

被折叠的 条评论
为什么被折叠?



