//翻转某一范围内的链表(若范围过大不翻转)
struct ListNode* reverseList(struct ListNode* head, int len)
{
if(head == NULL || len < 2)
return head;
struct ListNode* tail = head;
while(--len){
if(tail->next == NULL)
return head;
tail = tail->next;
}
struct ListNode* i = head;
struct ListNode* j = i->next;
struct ListNode* k;
while(i != tail){
k = j->next;
j->next = i;
i = j;
j = k;
}
head->next = j;
return tail;
}
struct ListNode* reverseKGroup(struct ListNode* head, int k){
struct ListNode ret_h;//保存返回的新头
ret_h.next = head;//head复用为当前组链表旧头(新尾巴)
struct ListNode* Prev_t = &ret_h;//上一组链表的尾巴
struct ListNode* new_h;//当前组链表的新头
do{
new_h = reverseList(head,k);
Prev_t->next = new_h;
Prev_t = head;
head = head->next;
} while(new_h != Prev_t && head != NULL);
return ret_h.next;
}
25-困难- K 个一组翻转链表[C语言]
最新推荐文章于 2024-08-10 22:52:22 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)