#ifndef LinkList_hpp
#define LinkList_hpp
typedef struct Node{
int data;
Node* next;
Node* pre;
}Node;
class LinkList{
private:
Node *head;
Node *tail;
int length;
public:
LinkList();
//分配內(nèi)存,構(gòu)建節(jié)點
Node* makeNode();
//添加節(jié)點到鏈表尾
bool push(int data);
//彈出鏈表最后一個節(jié)點,并返回值
int pop();
//通過index來查找鏈表中的元素
int objectAt(int index);
//插入元素到指定位置的前方
bool insert(int index,int data);
//打印鏈表的所有元素
void display();
};
#endif /* LinkList_hpp */
#include "LinkList.hpp"
#include <iostream>
#include <mm_malloc.h>
using namespace std;
LinkList::LinkList(){
head = makeNode();
tail = head;
length = 0;
}
Node * LinkList::makeNode(){
Node* node = (Node*)malloc(sizeof(Node));
return node;
}
bool LinkList::push(int data){
Node *node = makeNode();
if(!node){
return false;
}
node->data = data;
node->pre = tail;
tail->next = node;
tail = node;
length ++;
return true;
}
int LinkList::pop(){
int data = 0;
Node* node = head->next;
while (node->next) {
node = node->next;
}
data = node->data;
tail = node->pre;
tail->next = node->next;
length--;
free(node);
node = NULL;
return data;
}
int LinkList::objectAt(int index){
if(index<1 || index > length){
return 0;
}
int data = 0;
Node* q = head;
for(int i=0; i < index;i++){
q = q->next;
}
data = q->data;
return data;
}
bool LinkList::insert(int index, int data){
if(index<1 || index> length){
return false;
}
Node *p = makeNode();
p->data = data;
Node *q = head;
for(int i=0; i < index; i++){
q = q->next;
}
p->pre = q->pre;
p->next = q;
q->pre->next = p;
q->pre = p;
length ++;
return true;
}
void LinkList::display(){
Node *n = head->next;
cout<<"data:";
while (n) {
cout<<n->data<<" ";
n = n->next;
}
cout << endl;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。