将一个链表后K个结点移到链表头

来源:互联网 发布:ajax post提交json 编辑:程序博客网 时间:2024/05/29 19:57

例如:给定链表: 1->2->3->4->5->NULL ; k = 2或k = 7
翻转后的结果为: 4->5->1->2->3->NULL.

解题思路:(1)将单链表转换成循环链表
(2)根据K值确定新链表头的位置

struct ListNode* rotateRight(struct ListNode* head, int k) {

if (head == NULL || k == 0)    return head;struct ListNode* head1 = head;int count = 1;while (head1->next != NULL){    head1 = head1->next;    count++;//计算链表的结点总数}head1->next = head;k = count - k%count - 1;while (k--){    head = head->next;}struct ListNode* newhead = head->next;head->next = NULL;return newhead;

}

0 0