#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define NULL 0 //代表空指針
typedef int status;
typedef int elemtype;
typedef struct LNode{
elemtype data; //數據域
struct LNode * next; //指針域
}LNode,*linklist;
status listcreate(linklist &L,elemtype n)//創建
{
LNode *p1,*p2;
L=(linklist)malloc(sizeof(LNode));
L->next=NULL;
p1=L;//L始終指向頭結點,L不能指向其他節點(不能後移),必須另外定義指針P1,P1開始指向L,之後P1可以後移
for(int i=0;i<n;i++)
{
p2=(LNode*)malloc(sizeof(LNode));
if(!p2) return ERROR;
printf("input data :");
scanf("%d", &p2->data );//別忘&
p1->next=p2;//L->next=p2是錯誤的
p1=p2;//指針後移
p2->next=NULL;
}
return OK;
}
status listinsert(linklist &L,int i,elemtype e)//插入
{
LNode *p=L,*q;
int j=0;
while(p && j<i-1)
{p=p->next;j++;}
q=(LNode *)malloc(sizeof(LNode));
if(!q) return ERROR;
q->data=e;
q->next=p->next;
p->next=q;
return OK;
}
status listreserve(linklist &L)//逆序
{
LNode *h=L->next,*p1=NULL,*p2=NULL;
while(h)
{
p2=h->next;
h->next=p1;
p1=h;
h=p2;
}
L->next=p1;//注意是從L後的第一個節點開始,所以不是L=P1
return OK;
}
status listprint(linklist L)
{
LNode *p;
p=L->next;//注意這裏P指向鏈表的第一個節點,p=L;p將指向L的頭結點,下面輸出應爲p->next->data
while(p)
{
printf(" %d ",p->data);
p=p->next;
}
printf("\n");
return OK;
}
void main()
{
linklist L;int n=3;
listcreate(L,n);
printf("創建鏈表爲:\n");
listprint(L);
listinsert(L,2,3);
listinsert(L,1,9);
printf("插入元素後鏈表爲:\n");
listprint(L);
listreserve(L);
printf("逆序後鏈表爲:\n");
listprint(L);
}