双向链表
#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;
pnode->data = n;
pnode->next = NULL;
pnode->prev = NULL;
return pnode;
}
插入结点(头插)
void InsertNode(struct mylist* L, int n) {
struct node* p = L->head->next;
while (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;
}
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;
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;
}
}
}
}