单链表的创建(头插法、尾插法)、插入、删除

//头插发创建链表(链表逆置),在第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;
}


  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值