欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据结构之单链表插入删除操作

程序员文章站 2022-03-22 20:00:29
...
#include<iostream>
using namespace std;
typedef struct LNode {
	int data;
	struct LNode *next;
}LNode;
void createListR(LNode *C, int a[], int n);//尾插法建立单链表
void createListF(LNode *C, int a[], int n);//头插法建立单链表
void traversal(LNode *C);
int getLength(LNode *C);
void deleteLNode(LNode *C,int n,int l);//删除第n项
void  insertLNodeR(LNode *C, int n, int e,int l);//在第n处尾插法插入数字e
int main() {
	LNode *C;
	C = (LNode *)malloc(sizeof(LNode));//C为头指针,并且指向头结点
	C->next = NULL;
	int a[6] = { 1,2,3,4,5,6 };
	/////////////创建单链表
	createListF(C, a, 4);
	traversal(C);
	cout << "该单链表长度为:" << getLength(C) << endl;
	////////////////插入
	insertLNodeR(C, 3, 999, getLength(C));
	traversal(C);
	cout << "该单链表长度为:" << getLength(C) << endl;
	////////////////删除
	deleteLNode(C, 2, getLength(C));
	traversal(C);
	cout << "该单链表长度为:" << getLength(C) << endl;
	///////////////
	return 0;
}
void createListR(LNode *C, int a[], int n) {
	LNode *s, *r;//s用来接收新结点,r用来始终指向终端结点
	r = C;
	for (int i = 0; i < n;++i) {
		s = (LNode *)malloc(sizeof(LNode));
		s->data = a[i];
		//关键步骤
		r->next = s;
		r = r->next;//尾指针后移
		//关键步骤
	}
	r->next = NULL;
}
void createListF(LNode *C, int a[], int n) {
	LNode *s;
	for (int i = 0; i < n; ++i) {
		s = (LNode *)malloc(sizeof(LNode));
		s->data = a[i];
		//关键步骤
		s->next = C->next;
		C->next = s;
		//关键步骤
	}
}
void traversal(LNode *C) {
	LNode *p;//用来指向头结点
	p = C;
	cout << "遍历结果为:";
	while ( (p->next)!=NULL ){
		p = p->next;//p指针后移
		cout << p->data << "   ";
	}
	cout << endl;
}
int getLength(LNode *C) {
	LNode *p;
	p = C;
	int l = 0;
	while ((p->next) != NULL) {
		++l;
		p = p->next;
	}
	return l;
}
void deleteLNode(LNode *C, int n,int l) {
	LNode *p;
	LNode *q;
	p = C;
	int m = 0;
	p = C;
	if (n<1 || n>l) {
		cout << "没有该项数!" << endl;
	}
	else {
		while (m<n-1) {
			p = p->next;
			++m;
		}
		//关键部分
		q = p->next;
		p->next=p->next->next;
	  //关键部分
		cout << "删除第" << n << "个数字" << endl;
		cout << "删除的数字是:" << q->data << endl;
	}
}
void insertLNodeR(LNode *C, int n, int e, int l) {
	LNode *p;
	LNode *s;//接收新结点
	s = (LNode *)malloc(sizeof(LNode));
	s->data = e;
	p = C;
	int m = 0;
	if (n<1 || n>l) {
		cout << "插入位置不合法!" << endl;
	}
	else {
		while (m<n ) {//若在插入位置之前插入数字,改为m<n-1
			p = p->next;
			++m;
		}
		s->next=p->next;
		p->next = s;
	}
	cout << "在第" << n << "处后" << "插入数字" << e << endl;
}
 

 

相关标签: C 数据结构