1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| #include<stdio.h> #include<malloc.h> typedef struct node{ int data; struct node *next; }node,*Lnode; Lnode creat(){//对链表赋值 Lnode head,p,q; head=(node*)malloc(sizeof(node)); q=head; char c; c=','; printf("input data:\n"); while(c!='.'){ int a; scanf("%d",&a); p=(node*)malloc(sizeof(node)); p->data=a; q->next=p;//连接下一个链表 q=p;//指向最新的链表 c=getchar();//输入.结束 } p->next=NULL;//最后一个指针指向空 return head;//返回头指针 } void exchange(Lnode n){//对单链表就地逆置 Lnode p,s,t; p=n;//让p指向头指针 s=p->next;//让s指向p1 while(s->next!=NULL){//当s指向最后一个,为空时结束循环 t=s->next;//让t指向p2 s->next=p;//把p1放到头指针前面 p=s;//让p指向新链表第一个结点 s=t;//此时s和t同时指向p2 }//p1放到头指针之前,第一次循环结束 s->next=p; //最后一个结点,放到最前面 n->next->next=NULL;//头指针的下一个是指向p1,逆向后是最后一个。让p1的next指向空 n->next=s;//让头指针指向新链表的最前端 } void print(node *n){//输出链表 printf("print:\n "); n=n->next;//从新的p1开始输出 while(n!=NULL) { printf("%d ",n->data); n=n->next; } } int main(){ node *n; n=creat(); exchange(n); print(n); return 0; }
|