数据结构实验一:线性表的插入和删除
实验要求1、建立线性表,可以顺序表或者链表。2、完成线性表的插入和删除操作。3、实验报告格式及图表清晰;4、如有雷同,均算抄袭,按零分处理。代码:#include<iostream>#include<stdio.h>#include<stdlib.h>#include <iostream>using namespace std;struct node
·
实验要求
1、建立线性表,可以顺序表或者链表。
2、完成线性表的插入和删除操作。
3、实验报告格式及图表清晰;
4、如有雷同,均算抄袭,按零分处理。
代码:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
struct node
{
int data;
struct node* next;
};
void add(struct node* h, int i, int x)//插在第i个数之后,如果i大于链表长度则插在链尾
{
struct node* p = h, * r;
if (h->data <= i) i = h->data;
int cnt = 0;
while (i != cnt) p = p->next, cnt++;
r = p->next;
struct node* q = (node*)malloc(sizeof(node));
q->data = x;
p->next = q;
q->next = r;
h->data++;
}
void ears(struct node* h, int i)//删除第i个元素
{
struct node* p = h, * r;
if (i > h->data || i == 0) {
cout << "没有该元素!" << endl;
return;
}
if (h->data == i) {
r = p;
while (p->next) r = p, p = p->next;
free(p);
r->next = NULL;
h->data--;
return;
}
int cnt = 1;
while (i != cnt) p = p->next, cnt++;
r = p->next;
p->next = r->next;
free(r);
h->data--;
}
struct node* init(int n)
{
struct node* h = (node*)malloc(sizeof(node));
h->data = 0;
struct node* p, * r;
p = (node*)malloc(sizeof(node));
cin >> p->data;
p->next = NULL;
h->data++;
h->next = p;
for (int i = 1; i < n; i++) {
r = (node*)malloc(sizeof(node));
cin >> r->data;
r->next = NULL;
h->data++;
p->next = r;
p = p->next;
}
return h;
}
void print(struct node* h)
{
cout << "链表中数据如下:";
struct node* r = h->next;
while (r) {
cout << r->data << ' ';
r = r->next;
}
putchar(10);
}
int main()
{
int n;
cout << "请输入链表长度" << endl;
cin >> n;
cout << "请输入" << n << "个数据" << endl;
struct node* head = init(n);
print(head);
int i, x;
cout << "输入插入位置和要插入的数: ";
cin >> i >> x;
add(head, i, x);
print(head);
cout << "输入删除位置: ";
cin >> i;
ears(head, i);
print(head);
return 0;
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)