这是一道微软的面试题改编而来,在浙大陈越姥姥的数据结构与算法课上看到,在这里整合一下。
1. 分解演示
2. 代码
Ptr Reverse( Ptr head, int K )
{
cnt = 1;
new = head->next;
old = new->next;
while( cnt < K ){
temp = old->next;
old->next = new;
new = old;
old = temp;
cnt++;
}
head->next->next = old;
return new;
}
3. 延伸
我认为这道题还可以改为:
把单链表的第M个结点到第N个结点反转,其他结点保持顺序不变;
struct ListNode* reverseList(struct ListNode* head,int M, int N){
struct ListNode * new;
struct ListNode * old;
struct ListNode * p;
int cnt=1;
//int M=3;
//int N=7;
if(head==NULL || head->next == NULL)
return head;
p = head;
for(int i=1; i<M-1; i++)
p = p->next;
new = p;
old = new->next;
while(cnt < (N-M+2)){
struct ListNode * tmp = old->next;
old->next = new;
new = old;
old = tmp;
cnt++;
}
p->next->next = old;
p->next = new;
return head;
}