题目链接:https://leetcode.com/problems/rotate-list/
/* 题意:给出一个链表,将链表向右旋转k个位置 */ /** *思路:右旋k个位置,相当与将链表从第len-k个位置截断,然后 * 将两截链表交换位置,重新链接成一个链表 * */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(head == NULL) return head; //空表,直接返回 ListNode *end; int len = GetLength(head, &end); k %= len; if(k == 0) return head; else { // int pre = len-k; ListNode *root = new ListNode(0); root->next = head; ListNode *curr = head; int index = 1; while(index != pre) { index ++; curr = curr->next; } //此时curr指向前半截链表的最后一个元素 //也即旋转链表后的最后一个元素 end->next = root->next; root->next = curr->next; curr->next = NULL; return root->next; } } //返回链表长度 //end指向链表的最后一个结点 int GetLength(ListNode *head, ListNode **end) { int len = 0; while(head != NULL) { len ++; *end = head; head = head->next; } return len; } };
时间: 2024-10-04 21:19:56