数据结构实验一——对链表插入,删除操作

#include “stdio.h”
#include “stdlib.h”
#include “io.h”
#include “math.h”
#include “time.h”
#include"string.h"
#include

using namespace std;

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20

typedef int Status;

typedef int QElemType;

typedef struct LNode
{
int num;
QElemType data;
struct LNode* next;
struct LNode* prior;
}LNode, * LinkedList;
//获取单链表长度 头结点无数据,不算
LinkedList CreateList_Head(LinkedList L)//尾插法创建链表
{
int x;
L = (LNode*)malloc(sizeof(LNode));
LNode* s, * r = L;
scanf_s("%d", &x);
while (x != 9999) {
s = (LNode*)malloc(sizeof(LNode)); //创建新的结点
s->data = x;
r->next = s;
r = s;
scanf_s("%d", &x);
}
r->next = NULL;
return L;
}
int ListLength(LinkedList L)
{
LinkedList p = L; int sum = 0;
while §
{
sum++;
p = p->next;
}
return sum - 1;//去除头结点
}
int ListInsert(LinkedList L, int pos, int data)
{
int i;
LinkedList p, q;
p = q = (LinkedList)malloc(sizeof(LinkedList));
p = L;
q->data = data;
q->next = NULL;
if (pos <= 0)
{
return -1;
}
for (i = 1; i <= pos - 1; i++)
{
p = p->next;
if (p->next == NULL && i < pos - 1)
{
return -1;
}
}
if (p->next != NULL)
{
p->next->prior = q;
}
q->next = p->next;
p->next = q;
q->prior = p;
return 1;
}

void PrintList(LinkedList& L)
{
LinkedList p = L->next;//跳过头结点
if (ListLength(L))
{
printf(“当前单链表所有元素:”);
while §
{
printf("%d “, p->data);
p = p->next;
}
printf(”\n");
}
else
{
printf(“当前单链表已空!\n”);
}
}
void ListDelete(LinkedList& L, int i)
{
LNode* p = L;
int j = 0;
//查找第i-1个结点,p指向该结点
while ((p->next) && (j < i - 1))
{
p = p->next;
j++;
}
if ((!p->next) || (j > i - 1))
printf(“位置错误!”); //i>n或i<1时,删除位置不合理
LNode* q = p->next; //临时保存被删除结点的地址以备释放
p->next = q->next; //改变删除结点前驱结点的指针域
delete q;
}
int main()
{

LinkedList L=0; int choice=0;
printf("尾插法建立单链表,输入值(9999结束)\n");
L = CreateList_Head(L);
PrintList(L);
while (choice ==0)
{
	cout << "请选择你想要进行的操作:" << endl;
	cout << "1.插入操作" << endl;
	cout << "2.删除操作" << endl;
	cout << "3.结束操作" << endl;
	int i;
	cin >> i;
	cout << i << endl;
	switch (i)
	{
	case 1:
		int m, n;
		cout << "请输入你想要在插入第几位元素:" << endl;
		cin >> m;
		cout << "请输入你想要插入的元素:" << endl;
		cin >> n;
		ListInsert(L, m, n);
		PrintList(L); break;
	case 2:
		int j;
		cout << "请输入你想要删除的元素位数:" << endl;
		cin >> j;
		ListDelete(L, j); 
		PrintList(L); break;
	case 3:choice++; break;
	default:cout << "错误!请重新选择" << endl;
	}
	
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值