チェーンテーブルの追加削除(補足待ち...)
にほうこうチェーンテーブル
作成
インサートノード
印刷
削除
選択ソート(値交換)
#include
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;
}
}
}
}