单链表的删除(自我练习)

#include<iostream>
using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE - 1
#define OVERFLOW - 2
#define MAXSIZE 100  
#define SIZE 4  
typedef int Status;

typedef struct Lnode {
	int data;
	struct Lnode* next;
}LNode, * LinkList;

Status InitList(LinkList& L) {
	L = new Lnode;
	L->next = NULL;
	return OK;
}

//后插法创建单链表
void CreateList_R(LinkList& L, int n) {
	InitList(L);
	LinkList r = L;
	for (int i = 0; i < n; i++) {
		LinkList p = new Lnode;
		cin >> p->data;
		p->next = r->next;
		r->next = p;
		r = p;
	}
}

Status ListDelete(LinkList& L, int i) {
	int j = 1;
	LinkList p = L;
	while ((p->next) && j < i) {
		p = p->next;
		j++;
	}
	if (!(p->next) && j > i) return ERROR;
	else {
		LinkList q = p->next;
		p->next = q->next;
		delete q;
		return OK;
	}
}

void RestElem(LinkList& L, int i) {
	Status res = ListDelete(L, i);
	if (res) {
		LinkList p = L->next;
		while (p)
		{
			cout << p->data << " ";
			p = p->next;
		}
	}
	else cout << "输入的下标有误" << endl;
}

int main() {
	LinkList L;
	int n;
	cout << "请输入单链表所插入的元素的个数" << endl;
	cin >> n;
	CreateList_R(L, n);
	int i;
	cout << "请输入需要删除的元素下标:" << endl;
	cin >> i;
	cout << "剩余元素为:" << endl;
	RestElem(L, i);
}

上一篇:第三周总结


下一篇:BJFUOJ:基于链式存储结构的图书信息表的创建和输出