電子商務(wù)網(wǎng)站開發(fā)平臺圖目前較好的crm系統(tǒng)
Description
用C++語言和類實現(xiàn)單鏈表,含頭結(jié)點
屬性包括:data數(shù)據(jù)域、next指針域
操作包括:插入、刪除、查找
注意:單鏈表不是數(shù)組,所以位置從1開始對應(yīng)首結(jié)點,頭結(jié)點不放數(shù)據(jù)
類定義參考
#include<iostream>
using namespace std;
#define ok 0
#define error -1// 鏈表結(jié)點定義
class ListNode
{
public:int data;ListNode *next;ListNode() {next = NULL;}
};
// 帶頭結(jié)點的單鏈表類定義
class LinkList
{
public:ListNode *head;int len;// 操作定義LinkList();~LinkList();ListNode *LL_index(int i); // 返回第i個結(jié)點的指針,如果不存在返回NULLint LL_get(int i); // 獲取第i個元素的數(shù)據(jù)int LL_insert(int i, int item); // 把數(shù)值item插入第i個位置int LL_del(int i); // 刪除第i個結(jié)點void LL_display(); // 輸出單鏈表的內(nèi)容
};
LinkList::LinkList()
{head = new ListNode();len = 0;
}
LinkList::~LinkList()
{ListNode *p, *q;p = head;while(p != NULL){q = p;p = p->next;delete q;}len = 0;head = NULL;
}
void LinkList::LL_display()
{ListNode *p;p = head->next;while(p){cout << p->data << ' ';p = p->next;}cout << endl;
}
Input
- 第1行先輸入n表示有n個數(shù)據(jù),接著輸入n個數(shù)據(jù)
- 第2行輸入要插入的位置和新數(shù)據(jù)
- 第3行輸入要插入的位置和新數(shù)據(jù)
- 第4行輸入要刪除的位置
- 第5行輸入要刪除的位置
- 第6行輸入要查找的位置
- 第7行輸入要查找的位置
Output
數(shù)據(jù)之間用空格隔開,
第1行輸出創(chuàng)建后的單鏈表的數(shù)據(jù)
每成功執(zhí)行一次操作(插入或刪除),輸出執(zhí)行后的單鏈表數(shù)據(jù)
每成功執(zhí)行一次查找,輸出查找到的數(shù)據(jù)
如果執(zhí)行操作失敗(包括插入、刪除、查找等失敗),輸出字符串error,不必輸出單鏈表
Sample
?
?AC代碼:
#include<iostream>
using namespace std;
#define ok 0
#define error -1// 鏈表結(jié)點定義
class ListNode
{
public:int data;ListNode* next;ListNode() { next = NULL; }
};
// 帶頭結(jié)點的單鏈表類定義
class LinkList
{
public:ListNode* head;int len;// 操作定義LinkList();ListNode* LL_index(int i) {}; // 返回第i個結(jié)點的指針,如果不存在返回NULLvoid LL_get(int i) {if (i <= 0 || i > len ) {cout << "error" << endl;}else {ListNode* p;p = head;for (int j = 0; j < i; j++) {p = p->next;}cout << p->data << endl;}}; // 獲取第i個元素的數(shù)據(jù)void LL_insert(int i, int item) {if (i <= 0 || i > len + 1) {cout << "error" << endl;}else {ListNode* p;p = head;for (int j = 1; j < i; j++) {p = p->next;}ListNode* s = new ListNode;s->data = item;s->next = p->next;p->next = s;p = s;len++;LL_display();}}; // 把數(shù)值item插入第i個位置void LL_del(int i) {if (i <= 0 || i > len) {cout << "error" << endl;}else {ListNode* p;p = head;for (int j = 1; j < i; j++) {p = p->next;}p->next = p->next->next;LL_display();len--;}}; // 刪除第i個結(jié)點void LL_display(); // 輸出單鏈表的內(nèi)容
};
LinkList::LinkList()
{head = new ListNode();len = 0;
}
void LinkList::LL_display()
{ListNode* p;p = head->next;while (p){cout << p->data << ' ';p = p->next;}cout << endl;
}int main() {int t;int data;cin >> t;LinkList L;ListNode* p;p = L.head;while (t--) {ListNode* s = new ListNode;L.len++;cin >> data;s->data = data;s->next = p->next;p->next = s;p = p->next;}L.LL_display();int i, item;cin >> i >> item;L.LL_insert(i, item);cin >> i >> item;L.LL_insert(i, item);cin >> i;L.LL_del(i);cin >> i;L.LL_del(i);cin >> i;L.LL_get(i);cin >> i;L.LL_get(i);
}