//头插发创建链表(链表逆置),在第i个位置插入节点,删除第i个位置节点
#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) //i表示位序
{
LNode *p;
scanf("%d",&i);
scanf("%d",&e);
if(i < 1)
return false;
p = L;
int j = 0; //j也是位序
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; //j也是位序
while(p != NULL && j < i-1) //找到第i-1个节点
{
p = p->next;
j++;
}
q = p->next;
p->next = q->next;
e = q->data;
free(q);
return true;
}
/**
LNode * GetNode(Linklist L ,int i)
{
scanf("%d",&i);
if(i < 1);
return NULL;
LNode *p;
p = L;
int j = 0;
while(p != NULL && j < i)
{
p = p->next;
j++;
}
return p;
}
***/
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);
//PrintList(GetNode(L,i));
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;
}
单链表的创建(头插法、尾插法)、插入、删除
最新推荐文章于 2024-07-24 23:27:53 发布