样例
给出链表1->2->3->4->5->null和k=2
返回4->5->1->2->3->null
我的代码:
ListNode * rotateRight(ListNode * head, int k) {
// write your code here
if(head == NULL || head->next == NULL)
return head;
// 判断链表长度
int len = 1;
ListNode* temp = head;
while(temp)
{
temp = temp->next;
len += 1;
}
// 找到要断开链表的节点,即p
ListNode* p = head;
for(int i=1; i
{
p = p->next;
}
// 把断开处的最后一个节点的指针域赋NULL
ListNode* headlast = p;
headlast->next = NULL;
// 把断开后的下一个节点插到newhead的后面
ListNode* newhead = new ListNode(0);
ListNode* q = p->next;
newhead->next = q;
ListNode* last;
while(q)
{
last = q;
q = q->next;
}
// last为最后一个节点,将之前的head链表插入到last后面
last->next = head;
return newhead->next;
}
报的错误是:Segmentation fault (core dumped)
请问问题出在哪?