#include <stdio.h>
#include<stdbool.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node* next;
}Node,*LinkedList;
bool InitList(LinkedList *L)
{
*L=(Node*)malloc(sizeof(Node));
if(*L==NULL)
return false;
(*L)->next=NULL;
return true;
}
bool ListInsert(LinkedList *L,int i ,int e)
{
if(i<1)
return false;
Node* s = (Node*)malloc(sizeof(Node));
if(s==NULL)
return false;
int j =0;
Node* p = *L;
while(p!=NULL&&j<i-1)
{
p=p->next;
j++;
}
if(p==NULL)
return false;
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
bool InsertNextNode(Node *p,int e)
{
if(p==NULL)
return false;
Node* s = (Node*)malloc(sizeof(Node));
if(s==NULL)
return false;
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
bool InsertBeforeNode(Node *p,int e)
{
if(p==NULL)
return false;
Node* s = (Node*)malloc(sizeof(Node));
if(s==NULL)
return false;
s->next=p->next;
p->next=s;
s->data=p->data;
p->data=e;
return true;
}
bool ListDelete(LinkedList *L,int i , int *e)
{
if(i<1)
return false;
Node* p =*L;
int j=0;
while(p!=NULL&&j<i-1)
{
p=p->next;
j++;
}
if(p==NULL||p->next==NULL)
return false;
Node *s = p->next;
*e=s->data;
p->next=s->next;
free(s);
return true;
}
bool DeleteNode(Node *p)
{
if(p==NULL)
return false;
if(p->next!=NULL)
{
Node* s=p->next;
p->data=s->data;
p->next=s->next;
free(s);
}
}
Node* GetElem(LinkedList L,int i)
{
Node* p = L;
if(i<1)
return NULL;
int j=0;
while(j<i&&p!=NULL)
{
p=p->next;
j++;
}
return p;
}
Node* LocateElem(LinkedList L,int e)
{
Node* p= L->next;
while(p->data!=e&&p!=NULL)
p=p->next;
return p;
}
int GetLength(LinkedList L)
{
int j =0;
Node* p=L->next;
while(p!=NULL)
{
j++;
p=p->next;
}
return j;
}
void ListTailInsert(LinkedList *L)
{
Node* s,*r=*L;
int x;
printf("请输入结点数据,-999结束:\n");
do
{
scanf("%d",&x);
s=(Node*)malloc(sizeof(Node));
s->data=x;
r->next=s;
r=s;
}while(x!=-999);
r->next=NULL;
}
void PrintList(LinkedList *L)
{
Node *p = (*L)->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
void ListHeadInsert(LinkedList *L)
{
Node* s;
int x;
printf("请输入结点数据,-999结束:\n");
do
{
scanf("%d",&x);
s=(Node*)malloc(sizeof(Node));
s->data=x;
s->next=(*L)->next;
(*L)->next=s;
}while(x!=-999);
}
int main () {
printf("Hello world! - c.jsrun.net.");
LinkedList L;
if(!InitList(&L))
{
return -1;
}
ListHeadInsert(&L);
PrintList(&L);
ListInsert(&L,4,4);
PrintList(L);
InsertNextNode(GetElem(L,3),5);
PrintList(&L);
int *e;
ListDelete(&L,4,e);
PrintList(&L);
printf("%d",LocateElem(L,3)->data);
return 0;
}