8579 链式线性表的基本操作(链表)

#include
#include
#define ERROR 0
#define OK 1
#define ElemType int
#include
using namespace std;
typedef struct LNode
{
 int data;
 struct LNode *next;
}LNode,*LinkList;

int CreateLink_L(LinkList &L,int n){
// 创建含有n个元素的单链表
  LinkList p,q;
  int i;
  ElemType e;
  L = (LinkList)malloc(sizeof(LNode));
  L->next = NULL;              // 先建立一个带头结点的单链表
  q = L;//我觉得直接用L也行
  for (i=0; i<n; i++) {
	 scanf("%d", &e);
    p = (LinkList)malloc(sizeof(LNode));  // 生成新结点
    p->data=e;
    q->next=p;
    p->next=NULL;
    q=p;
  }
  return OK;
}

int LoadLink_L(LinkList &L){
// 单链表遍历
 LinkList p = L->next;
 if(p==NULL)printf("The List is empty!");
 else
 {
	 printf("The LinkList is:");
	 while(p!=NULL)
	 {
		printf("%d ",p->data);
		p=p->next;
	 }
 }
 printf("\n");
 return OK;
}

int LinkInsert_L(LinkList &L,int i,ElemType e){

    LNode *p=L,*newnode;
    int j,k,m,n;
    newnode=(LNode *)malloc(sizeof(LNode));
    newnode->data=e;
    for(j=1;j<=i-1;j++) p=p->next;
    newnode->next=p->next;
    p->next=newnode;
    return OK;
}

int LinkDelete_L(LinkList &L,int i, ElemType &e){
    LNode *p=L,*h;
    for(int j=1;j<=i;j++)
    {
        h=p;//h存放前驱结点
        p=p->next;
    }
    h->next=p->next;
    e=p->data;
    return OK;
}

int main()
{
 LinkList T;
 int a,n,i;
 ElemType x, e;
 printf("Please input the init size of the linklist:\n");
 scanf("%d",&n);
 printf("Please input the %d element of the linklist:\n", n);
 if(CreateLink_L(T,n))     // 判断链表是否创建成功,请填空
 {
	 printf("A Link List Has Created.\n");
	 LoadLink_L(T);
 }
 while(1)
	{
		printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n");
		scanf("%d",&a);
		switch(a)
		{
			case 1: scanf("%d%d",&i,&x);
				  if(i<1||i>n+1||!LinkInsert_L(T,i,x)) printf("Insert Error!\n");
				  else {n++;printf("The Element %d is Successfully Inserted!\n", x);}//注意长度变化
				  break;
			case 2: scanf("%d",&i);
				  if(i<1||i>n||!LinkDelete_L(T,i,e)) printf("Delete Error!\n");
				  else {n--;printf("The Element %d is Successfully Deleted!\n", e);}//注意长度变化
				  break;
			case 3: LoadLink_L(T);
				  break;
			case 0: return 1;
		}
	}
}

你可能感兴趣的:(#,链栈列树)