奇怪我好像總是有多餘的檢查在回圈裡面?!
但是因為很快就accept了所以不想再追究了(遮臉)
C 真是 Linked list 的好朋友啊~~~~~
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k){
if (head == NULL || k==0 || head->next == NULL)
return head;
int length=0;
struct ListNode* pRun = head;
while(pRun!=NULL)
{
length++;
if (pRun->next==NULL)
break;
pRun=pRun->next;
}
pRun->next=head;
int stop = length - k%length;
for(int rotate=0; rotate <stop;rotate++)
{
if (rotate+1 ==stop)
pRun = head;
head = head->next;
}
pRun->next = NULL;
return head;
}
[20240811 update] 重新寫了一次,整個思維好像很不一樣了呢(?)
struct ListNode* rotateRight(struct ListNode* head, int k){
int count =0;
struct ListNode* ptr = head;
struct ListNode* pre, *tail;
while (ptr != NULL)
{
pre = ptr;
ptr = ptr->next;
count++;
}
if (count <=1)
return head;
tail = pre;
int _k = k%count;
int step = 0;
ptr = head;
while (step < (count - _k))
{
pre = ptr;
ptr = ptr->next;
step++;
}
tail->next = head;
head = pre->next;
pre->next = NULL;
return head;
}
修改了一下扣的長度可以變短,但是count 要小心
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k){
if (head == NULL || head ->next == NULL)
return head;
int count =0;
struct ListNode* ptr = head;
struct ListNode* pre;
while (ptr->next != NULL)
{
ptr = ptr->next;
count++;
}
count++;
ptr->next = head;
int _k = k%count;
int step = 0;
ptr = head;
while (step < (count - _k))
{
pre = ptr;
ptr = ptr->next;
step++;
}
head = pre->next;
pre->next = NULL;
return head;
}
沒有留言:
張貼留言