a***e 发帖数: 413 | 1 Update:
终于写出来了。。。。。去掉prev2 = p->next;就对了。
还是欢迎大牛们指点,讨论哈!哎,不知哪年哪月才能练到能去面试的。。。。。。
独自刷题非常郁闷。
Reverse Nodes in k-Group
https://oj.leetcode.com/problems/reverse-nodes-in-k-group/
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
My wrong answer!
ListNode *reverseKGroup(ListNode *head, int k) {
if (head==NULL||head->next==NULL||k<=1) return head;
ListNode *dummy = new ListNode(-1);
dummy->next = head;
ListNode *p = head;
ListNode *prev = dummy;
ListNode *prev2=prev->next;
while(p!=NULL)
{
int c=0;
for (c=0;c
{
p=p->next;
}
if (c<=k-1 && p==NULL)
return dummy->next;
else //reverse k nodes
{
ListNode *p2 = p;
ListNode *tmp = p;
for (p=prev->next->next;p!=p2;)
{
tmp = p->next;
p->next = prev->next;
prev2->next = tmp;
prev->next = p;
// prev2 = p->next;
p = tmp;
}
prev = prev2;
}
}
return dummy->next;
} | A*****i 发帖数: 3587 | 2 翻转链表被面到不下5次,从刚毕业就开始练习也练了无数次
但是每次做的时候还是需要想很久,不知道为什么,别的类型题做一遍基本上脑子里就
有印象了但翻转链表这个做一百遍还跟没做效果一样 |
|