1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#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();
//分配内存,构建节点
Node* makeNode();
//添加节点到链表尾
bool push(int data);
//弹出链表最后一个节点,并返回值
int pop();
//通过index来查找链表中的元素
int objectAt(int index);
//插入元素到指定位置的前方
bool insert(int index,int data);
//打印链表的所有元素
void display();
};

#endif /* LinkList_hpp */
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#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;
}