对此题目的完整示例可直接运行代码如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 typedef struct LNode{ 4 int data; 5 struct LNode *next; 6 }LNode; 7 LNode* creat(int n){ 8 LNode *Link; 9 LNode *p1,*p2; 10 int data; 11 Link=(LNode*)malloc(sizeof(LNode)); 12 p2=Link; 13 for(int i=0;i<n;++i){ //一共n个数 14 scanf("%d",&data); 15 p1=(LNode*)malloc(sizeof(LNode)); 16 p1->data=data; 17 p2->next=p1; 18 p2=p1; 19 } 20 p2->next=NULL; 21 return Link; 22 } 23 24 LNode* reverseList(LNode *&A,int X,int Y){ //传过来的链表发生了逆置的变化,所以加个&符合 25 LNode *L; 26 L=A->next; //用哨兵指针L指向链表的第一个结点 27 LNode *p,*q,*t; 28 while(L->next!=NULL){ 29 if(L->next->data>X){ 30 p=L; //p指向了大于X的结点的前一个结点 31 // printf("%d ",p->data); 32 break; 33 } 34 L=L->next; 35 } 36 while(L->next!=NULL){ 37 if(L->next->data>=Y){ 38 q=L; //q指向了最后小于Y的结点 39 // printf("%d ",q->data); 40 break; 41 } 42 L=L->next; 43 } 44 while(p->next!=q){ 45 t=p->next; 46 p->next=t->next; 47 t->next=q->next; 48 q->next=t; 49 } 50 return A; 51 } 52 53 void print(LNode *Link){ 54 LNode *p; 55 p=Link->next; 56 while(p!=NULL){ 57 printf("%d",p->data); 58 printf(" "); 59 p=p->next; 60 } 61 printf(" "); 62 } 63 64 int main(){ 65 LNode *Link=NULL; 66 int X,Y; 67 int num; 68 printf("共创建几个链表结点:"); 69 scanf("%d",&num); 70 printf("请输入链表结点: "); 71 Link=creat(num); 72 printf("已创建好的链表结点:"); 73 print(Link); 74 printf("请输入X:"); 75 scanf("%d",&X); 76 printf("请输入Y:"); 77 scanf("%d",&Y); 78 reverseList(Link,X,Y); 79 printf("将大于X小于Y的所有结点逆置后的链表结点:"); 80 print(Link); 81 return 0; 82 }
运行结果如下: