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

链表 增删排查(待补充…)

程序员文章站 2022-05-13 16:02:37
...

双向链表

#include <iostream>
using namespace std;
struct mylist* GetList();
struct node* GetNode(int n);
void PrintList(struct mylist* L);
void InsertNode(struct mylist* L, int n);
void DeleteNode(struct mylist* L, int n);
void SelectionSort(struct mylist* L, int n);

struct mylist {//头结点
	struct node* head;
	struct node* tail;
	int size;
};

struct node {//结点
	int data;
	struct node* next;
	struct node* prev;
};


创建

int main()
{
	struct mylist* L = GetList();
	int i, val;
	for (i = 0; i < 5; i++) {
		cout << "input a num:" << endl;
		cin >> val;
		InsertNode(L, val);
		PrintList(L);
	}

	cout << "input a num for insertion:" << endl;
	cin >> val;
	InsertNode(L, val);
	PrintList(L);

	cout << "input a num for deletion:" << endl;
	cin >> val;
	DeleteNode(L, val);
	PrintList(L);

	cout << "After sorting:" << endl;
	SelectionSort(L,val);
	PrintList(L);
	return 0;
}

struct mylist* GetList() {
	struct mylist* L = new struct mylist;
	L->head = GetNode(0);
	L->tail = GetNode(0);
	L->head->next = L->tail;
	L->tail->prev = L->head;
	L->size = 0;
	return L;
}

struct node* GetNode(int n) {
	struct node* pnode = new struct node;//(struct node*)malloc(sizeof(struct node))
	pnode->data = n;
	pnode->next = NULL;
	pnode->prev = NULL;
	return pnode;
}

插入结点(头插)

void InsertNode(struct mylist* L, int n) {//头插
	struct node* p = L->head->next;//声明一个节点p,让p指向链表的第一个节点
	while (p != L->tail) {
			struct node* newNode = GetNode(n);
			newNode->next = p;//p赋值给新节点后继
			newNode->prev = p->prev;//p-prev赋值给新节点前驱

			/*这两条语句顺序不能变,不然会使得p->prev提前变为新节点*/

			p->prev->next = newNode;//新节点赋给p-prev的后继
			p->prev = newNode;//新节点赋给p的前驱
			L->size++;
			return;
	}
	/* 此时p指向 L->tail */
	struct node* newNode = GetNode(n);
	newNode->next = p;
	newNode->prev = p->prev;
	p->prev->next = newNode;
	p->prev = newNode;
	L->size++;
	return;
}

打印

void PrintList(struct mylist* L) {
	struct node* p = L->head->next;
	while (p != L->tail) {
		cout << p->data << "  ";
		p = p->next;
	}
	cout << endl;
}

删除

void DeleteNode(struct mylist* L, int n) {
	struct node* p = L->head->next;
	while (p != L->tail) {
		if (n == p->data) {
			p->prev->next = p->next;
			p->next->prev = p->prev;
			delete p; //free(p)
			L->size--;
			return;
		}
		p = p->next;
	}
	cout << "the number does not exist" << endl;
}

选择排序(值交换)

void SelectionSort(struct mylist* L, int val)
{
	struct node* p = NULL;
	struct node* q = NULL;
	for (p = L->head->next; p != L->tail; p = p->next) {
		for (q = p->next; q != L->tail; q = q->next) {
			if (p->data > q->data) {
				int tmp = q->data;
				q->data = p->data;
				p->data = tmp;
			}
		}
	}
}
相关标签: 链表 c++