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
基本思路就是每经过k个节点就反转一次即可
class Solution { public: ListNode *reverse(ListNode* head, ListNode* tail){ ListNode *newHead = NULL,*p = head; while(p!=tail){ ListNode* tmp = p->next; p->next = newHead; newHead = p; p = tmp; } return newHead; } ListNode *reverseKGroup(ListNode *head, int k) { ListNode* newHead = new ListNode(0),*newPre = newHead; newHead->next = head; ListNode* p = head,*pre = head; int cnt = 0; while(p){ cnt++; ListNode *tmp = p->next; if(cnt == k){ newPre->next = reverse(pre,p->next); newPre = pre; pre = tmp; cnt = 0; } p = tmp; } newPre->next = pre; return newHead->next; } };
Leetcode Reverse Nodes in k-Group,布布扣,bubuko.com
时间: 2024-12-26 01:03:29