1. 程式人生 > >資料結構之單鏈表插入刪除操作

資料結構之單鏈表插入刪除操作

#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;
}