Reserve函数
void ReverseList(pLink plink)
{
pNode p1,p2,p3;
p1=plink->head->next;
p2=p1->next;
p1->next = NULL;
while (p2) {
p3=p2->next;
p2 ->next = p1;
p1 = p2;
p2 = p3;
}
plink->head->next = p1;
return ;
}
对应的链表和相应操作
#include <stdio.h>
#include <stdlib.h>
typedef int Elementtype;
typedef struct node {
Elementtype data;
struct node* next;
} Node,*pNode ;
typedef struct {
Node *head,*tail;
} Link,*pLink;
pLink CreateList(void);
void AddFromHead(pLink plink,Elementtype data);
void AddFromTail(pLink plink,Elementtype data);
void PrintList(pLink plink);
void ReverseList(pLink);
void FreeList(pLink);
int main()
{
FILE* fp= fopen("review.in","r");
int n;
pLink plink = CreateList();
while (fscanf(fp,"%d",&n) != EOF) {
//AddFromHead(plink,n);
AddFromTail(plink,n);
}
PrintList(plink);
ReverseList(plink);
PrintList(plink);
FreeList(plink);
fclose(fp);
return 0;
}
pLink CreateList(void)
{
pLink plink = (pLink)malloc(sizeof(Link));
plink->head = plink->tail = (pNode)malloc(sizeof(Node));
plink->head->next = NULL;
return plink;
}
void AddFromHead(pLink plink,Elementtype data)
{
pNode p = (pNode)malloc(sizeof(Node));
p->data = data;
p->next = plink->head->next;
plink->head->next = p;
return ;
}
void AddFromTail(pLink plink,Elementtype data)
{
pNode p = (pNode)malloc(sizeof(Node));
plink->tail->next = p;
p->next = NULL;
p->data = data;
plink->tail = p;
return ;
/*
pNode q,end,p = (pNode)malloc(sizeof(Node));
for (q=end; q ;q=q->next) {
end = q;
}
p->data =data;
end->next = p;
p->next = NULL;
return ;
*/
}
void PrintList (pLink plink)
{
pNode p;
for (p=plink->head->next;p;p=p->next) {
printf("%d ",p->data);
}
printf("\n");
return ;
}
void ReverseList(pLink plink)
{
pNode p1,p2,p3;
p1=plink->head->next;
p2=p1->next;
p1->next = NULL;
while (p2) {
p3=p2->next;
p2 ->next = p1;
p1 = p2;
p2 = p3;
}
plink->head->next = p1;
return ;
}
void FreeList(pLink plink)
{
pNode p,q;
for (q=plink->head,p=plink->head->next;p;q=p,p=p->next) {
free(q);
}
free(q);
free(plink);
return ;
}