双向链表实现,通过C++实现

#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 */
#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;
}

最新文章

  1. VisualStudio控制台输出窗口一闪而过
  2. cursor or set-based
  3. 捷波朗 jabra BT3030 蓝牙耳机
  4. C++学习基础二——指针与引用的区别
  5. Maven运行时异常java.lang.UnsupportedClassVersionError的解决方案
  6. [上传下载] C# UpLoadFiles文件上传类 (转载)
  7. SQLyog之MySQL客户端的下载、安装和使用
  8. JAVA GC之标记 第五节
  9. Python:generator的send()方法流程分析
  10. MySQL两大存储引擎InnoDB与MyISAM
  11. (N叉树 BFS) leetcode429. N-ary Tree Level Order Traversal
  12. Lesson 1-2
  13. 城市扩张实验---ARCGIS处理踩雷
  14. 【20190129】CSS-定位问题记录
  15. octave基本指令4
  16. java.util.concuttent Callable Future详解
  17. matplotlib --&gt; r`$...$`
  18. Ubuntu install mysql database
  19. 顺序容器----顺序容器操作,vector对象如何增长,额外的string操作,容器适配器
  20. 用Visual C#来清空回收站(2)

热门文章

  1. Wireshark抓本地回环
  2. 多态&amp;接口
  3. UVa修改版02
  4. 【技术累积】【点】【java】【9】Optional
  5. chrome模拟微信
  6. swift的计算属性和懒加载
  7. Python基础:使用list &amp; tuple
  8. Smallest Common Multiple FreeCodeCamp
  9. LINUX KERNEL启动参数
  10. Docker:分布式系统的软件工程革命(上)