C++實現線性錶鏈式儲存結構的建立插入和刪除
阿新 • • 發佈:2019-01-27
主函式為:
#include <iostream>
using namespace std;
typedef int eletype;
struct Node
{
eletype data;
Node * next;
};
//typedef struct Node *LinkList;
void createLinkList(Node * L, int n);
void showLinkList(const Node * L, int n);
void insertLinkList(Node * L, int location, Node * e, int & n);
void deleteLinkList(Node * L, int location, int & n);
void clearLinkList(Node * L, int & n);
int main()
{
int number;
cout << "Please enter the number of linklist: ";
cin >> number;
Node * LinkList; //連結串列的頭指標
LinkList = (Node *)malloc(sizeof(Node)); //為連結串列動態分配儲存空間
LinkList->next = NULL;
LinkList->data = number; //頭指標的初始化
createLinkList(LinkList, number);
showLinkList(LinkList, number);
//實現在第loaction1位置處插入節點e
int location1;
cout << "Please enter a location of insert: ";
cin >> location1;
while (location1<=0 || location1>number+1)
{
cout << "The loaction input is error, please enter a location ranges 1 to " << number+1 << endl;
cout << "Please enter a location again: ";
cin >> location1;
}
Node * e;
e = (Node *)malloc(sizeof(Node));
cout << "Please enter the element of insert: ";
cin >> e->data;
insertLinkList(LinkList, location1, e, number);
showLinkList(LinkList, number);
//實現在location2位置處實現刪除節點e
int location2;
cout << "Please enter a location of delete: ";
cin >> location2;
while (location2<=0 || location2>number)
{
cout << "The loaction input is error, please enter a location ranges 1 to " << number << endl;
cout << "Please enter a location again:";
cin >> location2;
}
deleteLinkList(LinkList, location2, number);
showLinkList(LinkList, number);
//實現單鏈表的整表刪除
clearLinkList(LinkList, number);
cout << "The number of data is " << number << endl;
system("pause");
return 0;
}
建立線性表的鏈式儲存結構表函式為:
void createLinkList(Node * L, int n)
{
Node * p;
for (int i = 0; i < n; i++)
{
p = (Node *)malloc(sizeof(Node));
cout << "Please enter the data of " << n-i << "-th:";
cin >> p->data;
p->next = L->next;
L->next = p;
}
}
對鏈式儲存結構插入一個節點函式為:
void insertLinkList(Node * L, int location, Node * e, int & n)
{
for (int i = 0; i < location-1; i++)
{
L = L->next;
}
e->next = L->next;
L->next = e;
n++;
}
對鏈式儲存結構刪除一個節點的函式為:
void deleteLinkList(Node * L, int location, int & n)
{
Node * e;
for (int j = 0; j < location-1; j++)
{
L = L->next;
}
e = L->next;
cout << "The delete emelemt is " << e->data << endl;
L->next = e->next;
free(e);
n--;
}
顯示鏈式儲存結構中的元素和地址的函式為:
void showLinkList(const Node * L, int n)
{
Node * p;
p = L->next;
for (int i = 0; i < n; i++)
{
cout << "the data of " << i+1 << "-th is " << p->data << endl;
cout << "The " << i+1 << "-th address is " << p << endl;
p = p->next;
}
}
單鏈表整表刪除的函式為:
void clearLinkList(Node * L, int & n)
{
int number = n;
for (int i = 0; i < number; i++)
{
Node * q;
q = L->next;
L->next = q->next;
free(q);
n--;
}
L->next = NULL;
}
這是我自己的程式碼實現,如果你有什麼好的程式碼實現方法希望可以互相學習。