/*********************************************************** * Copyright (C), 2012-2013, Cgema Tech. Co., Ltd. * FileName : test.c * Author : Cgema * Version : 1.0 * Date : 2013.9.13 * Description : 单链表的翻转 * 原链表长度不知,可能是奇数也可能是偶数 * 若原链表为:h->1->2->3->4->5->6->7,则: * k=2时,将链表翻转为h->2->1->4->3->6->5->7 * k=3时,将链表翻转为h->3->2->1->6->5->4->7 * k=4时,将链表翻转为h->4->3->2->1->5->6->7 * 若原链表为:h->1->2->3->4->5->6->7->8,则: * k=4时,将链表翻转为h->4->3->2->1->8->7->6->5 * Source : 美团网2013笔试题 ***********************************************************/ #include<stdio.h> #include<stdlib.h> #define k 3 #define length 8 int main() { typedef struct node { int num; struct node *next; }*List,Node; int i,n = 0; Node *p,*q,*s,*w; List head = (Node *)malloc(sizeof(Node)); head->next = NULL; q = head; for(i=0; i<length; i++) //create linklist with tail { p = (Node *)malloc(sizeof(Node)); p->num = i+1; p->next = q->next; q->next = p; q = p; printf("p->num=%d ",p->num); } printf("linklist data init success! "); w = head; q = p = head->next; while(p) { n++; if(n == k) //opposite linklist operate { s = q->next; w->next = p->next; p->next = NULL; p = w->next; while(q) { q->next = w->next; w->next = q; q = s; if(s) s = s->next; } q = p; if(q) s = q->next; w = head->next; while(w->next != p) w = w->next; n = 0; printf("opposite linklist operate. "); } else p = p->next; } if(n != 0) printf("最后一组%d不够%d个结点,不可翻转! ",n,k); else printf("全部翻转完毕! ",n); p = head->next; //free linklist node q = head; while(p) { printf("p->num=%d ",p->num); free(q); q = p; p = p->next; } return 0; }