#include<stdio.h> #include<malloc.h>
typedef struct LNode
{
int data;
struct LNode *next;
};
LNode *Init_LNode()
{
LNode *head;
head=(LNode *)malloc(sizeof(LNode));
head->next=NULL; return (head);
}
LNode *Create_LNode(LNode *head)
{// Create a tail plug
LNode *newp,*p;
int a; p=head;
printf ( "Please enter a linked list data a: \ n");
scanf("%d",&a);
while(a!=-1)
{
newp=(LNode *)malloc(sizeof(LNode));
newp->data=a;
newp->next=NULL;
p->next=newp;
p=newp;
scanf("%d",&a);
}
return head;
}
LNode *Insert_LNode(LNode *head)
{// end inserted LNode * newp, * q;
int a; printf ( "Please enter the data to be inserted:");
scanf("%d",&a); while(a!=-1)
{
newp=(LNode *)malloc(sizeof(LNode));
newp->data=a;
newp->next=head->next;//头插
head->next=newp;
scanf("%d",&a);
}
return head;
}
LNode *delete_byValue(LNode *head)
{// delete by value
LNode *p,*q;
into you;
printf ( "Enter the number to be deleted: \ n");
scanf("%d",&e);
q=head;
p=head->next;
while(p!=NULL&&p->data!=e)
{
q=p; p=p->next;
}
if(p==NULL)
{
printf ( "element is not present \ n");
}
else
{
q->next=p->next; free(p);
}
return head;
}
LNode *delete_byID(LNode *head)
{// To remove the first several elements
LNode *p,*q; int i=0,j;
printf ( "Please enter the first few elements to be deleted: \ n");
scanf("%d",&j);
q=head;
p=head->next;
while(p!=NULL&&i<j-1)
{
q=p; p=p->next; i++;
}
if(p==NULL)
{
printf ( "you want to delete does not exist \ n");
}
else
{
q->next=p->next; free(p);
}
return head;
}
void print(LNode *head)
{
LNode *p; p=head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next; }
printf("\n");
}
int main ()
{
LNode *head;
head=Init_LNode();
head=Create_LNode(head);
print(head); head=Insert_LNode(head); print(head);//输出 //head=delete_value(head); head=delete_byID(head); print(head); return 0;
}