链表倒置
#include"stdio.h"#include"malloc.h"
#include"stdlib.h"
#define SIZE sizeof(snode)
typedef struct student
{
int num;
struct student *next;
}snode;
snode *create(); //创建链表
void print(snode *head); //打印链表
void invert(snode *&head); //为什么是 *& 呢?????????????而不是 snode *head
void main(void)
{
int m,k;
snode *head,head1;
head=create();
print(head);
printf("\n\n\n");
printf("链表逆置后结果为:\n");
invert(head);
print(head);
}
snode *create()
{
snode *head,*p,*q;
p=q=(snode *)malloc(sizeof(SIZE));
head=(snode *)malloc(sizeof(SIZE));
int n=0,num1;
FILE *fp;
fp=fopen("D:\\qq.txt","r");
fscanf(fp,"%d",&num1);
p->num=num1;
while(!feof(fp))
{
n++;
if(n==1)
head=p;
else
q->next=p;
q=p;
p=(snode *)malloc(sizeof(SIZE));
fscanf(fp,"%d",&num1);
p->num=num1;
}
q->next=NULL;
return (head);
}
void print(snode *head)
{
snode *p;
p=head; //带头结点
while(p!=NULL)
{
printf("%6d",p->num);
p=p->next;
}
}
void invert (snode *&head) //为什么是 *& 呢?????????????而不是 snode *head
{
snode *p,*q,*r;
p=head;
q=p->next;
while(q!=NULL)
{
r=q->next;
q->next=p;
p=q;
q=r;
}
head->next=NULL;
head=p;
}