#include<stdio.h>
#include<stdlib.h>
typedef struct LNode{
int data;
struct LNode * next;
}LNode,*Linklist;
bool List_headInsert(Linklist &L)
{
LNode *s;
int x;
L = (Linklist)malloc(sizeof(LNode));
L->next = NULL;
scanf("%d",&x);
while(x != 9999)
{
s = (Linklist)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d",&x);
}
return L;
}
bool InsertNextNode(LNode *p,int e)
{
if (p == NULL)
return false;
LNode *s;
s = (Linklist)malloc(sizeof(LNode));
s->next = p->next;
p->next = s;
s->data = e;
return true;
}
bool InsertI(Linklist &L,int i,int e)
{
LNode *p;
scanf("%d",&i);
scanf("%d",&e);
if(i < 1)
return false;
p = L;
int j = 0;
while(p != NULL && j < i-1)
{
p = p->next;
j++;
}
return InsertNextNode(p,e);
}
void PrintList(Linklist L)
{
L=L->next;
while(L!=NULL)
{
printf("%3d",L->data);
L=L->next;
}
printf("\n");
}
bool deleteNode(Linklist L,int i,int &e)
{
LNode *p;
LNode *q;
scanf("%d",&i);
if(i < 1)
return false;
p = L;
int j = 0;
while(p != NULL && j < i-1)
{
p = p->next;
j++;
}
q = p->next;
p->next = q->next;
e = q->data;
free(q);
return true;
}
int main()
{
Linklist L;
List_headInsert(L);
PrintList(L);
int i;
int e;
printf("请在第i个位置插入一个节点");
InsertI(L,i,e);
PrintList(L);
printf("请在第i个位置删除一个节点");
deleteNode(L,i,e);
PrintList(L);
return 0;
} ```
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode{
struct LNode * next;
int data;
}LNode,*Linklist;
bool List_TailInsert(Linklist &L)
{
int x;
L = (Linklist)malloc(sizeof(LNode));
L->next = NULL;
LNode *p;
LNode *r=L;
scanf("%d",&x);
while(x != 9999)
{
p = (Linklist)malloc(sizeof(LNode));
p->data = x;
r->next = p;
r = p;
scanf("%d",&x);
}
r->next = NULL;
return true;
}
void PrintList(Linklist L)
{
L=L->next;
while(L!=NULL)
{
printf("%3d",L->data);
L=L->next;
}
printf("\n");
}
int main()
{
Linklist L;
List_TailInsert(L);
PrintList(L);
return 0;
}