这里给出带有头结点和不带头结点的链表在内存中的实际情况,方便理解二者之间的不同之处
![这里给出带有头结点和不带头结点的链表在内存中的实际情况,方便理解二者之间的不同之处](https://i-blog.csdnimg.cn/blog_migrate/58889b99fdcb7a577508b00fabde35d9.png)
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}LNode,*LinkList;
bool InitList(LinkList &L){
L=(LNode *)malloc(sizeof(LNode));
if(L==NULL){
return false;
}
L->next=NULL;
return true;
}
LinkList List_HeadInsert(LinkList &L){
LNode *s;
int x;
InitList(L);
while(~scanf("%d",&x)){
s=(LNode *)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;
L->next=s;
}
return L;
}
LinkList List_TailInsert(LinkList &L){
InitList(L);
LNode *s,*r=L;
int x;
while(~scanf("%d",&x)){
s=(LNode *)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r=s;
}
r->next=NULL;
return L;
}
LNode *GetElem(LinkList &L,int i){
int j=1;
LNode *p=L->next;
if(i==0){
return L;
}
if(i<1){
return NULL;
}
while(j<i && p){
p=p->next;
j++;
}
return p;
}
LNode *LocateElem(LinkList &L,int e){
LNode *p=L->next;
while(p!=NULL && p->data!=e){
p=p->next;
}
return p;
}
bool Insert_TailListNode(LinkList &L,int i,int e){
LNode *p,*s;
p=GetElem(L,i-1);
if(p!=NULL){
s=(LNode *)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
return false;
}
bool Delete_ListNode(LinkList &L,int i){
LNode *p,*s;
p=GetElem(L,i-1);
if(p!=NULL){
p->next=p->next->next;
return true;
}
return false;
}
void PrintList(LinkList &L){
LNode *p=L->next;
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
}
int main(){
LinkList L;
List_TailInsert(L);
Delete_ListNode(L,2);
PrintList(L);
return 0;
}