您的位置:首页 > 编程语言 > C语言/C++

双向链表的C++实现 Implement of Doubly Linked List

2014-03-31 16:25 573 查看

实现了双向链表的以下功能  

头部插入节点  
尾部插入节点  
n-th位置插入节点  
n-th位置删除节点  
清空  
获取长度  
查找某个值

判断是否为空

#include <iostream>
using namespace std;
struct DoublyLinkedList
{
int val;
DoublyLinkedList *pre;
DoublyLinkedList *next;
};

void AddAtHead(DoublyLinkedList *&head, int data)
{
DoublyLinkedList *node = new DoublyLinkedList;
node->val = data;
node->pre = NULL;
node->next = NULL;

if(head != NULL)
{
node->next = head;
head->pre = node;
}
head = node;
}

//This function is different from the one in the implement of Linked List
//can add the node even though head is NULL by using *& instead of *
void AddAtTail(DoublyLinkedList *&head, int data)
{
DoublyLinkedList *node = new DoublyLinkedList;
node->val = data;
node->pre = NULL;
node->next = NULL;

if (head == NULL)
{
head = node;
return;
}

DoublyLinkedList *p = head; //must use another pointer as head is a reference
while(p->next != NULL)//move the pointer to the last node
p = p->next;

p->next = node;
node->pre = p;
}

void BuildDoublyLinkedList(DoublyLinkedList *&head,int a[], int n)
{
//AddAtHead(head,a[0]);
for (int i = 0; i < n; i++)
{
AddAtTail(head,a[i]);
}
}

void Traverse(DoublyLinkedList *head)
{
while (head!=NULL)
{
cout << head->val << " ";
head = head->next;
}
cout << "\n";
}

int GetSize(DoublyLinkedList *head)
{
int size = 0;
while (head!=NULL)
{
head = head->next;
size++;
}
return size;
}

bool IsEmpty(DoublyLinkedList *head)
{
if(head == NULL)
return true;
return false;
}

void MakeEmpty(DoublyLinkedList *&head)
{
while(head!=NULL)
{
DoublyLinkedList *p = head;
head = head->next;
delete p;
p = NULL;
}
}

bool Find(DoublyLinkedList *head, int data)
{
while (head != NULL)
{
if(head->val == data)
return true;
head = head->next;
}
return false;
}

void Insert(DoublyLinkedList *&head, int pos, int data)
{
if(pos < 1) return;

DoublyLinkedList *node = new DoublyLinkedList;
node->val = data;
node->pre = NULL;
node->next = NULL;

if (pos == 1)
{
node->next = head;
if(head != NULL)
head->pre = node;

head = node;
return;
}

DoublyLinkedList *p = head;
int cnt = 0;
while(cnt < pos-2 && p!=NULL)
{
p = p->next;
cnt++;
}

if(p == NULL) return;

node->pre = p;
node->next = p->next;
p->next = node;
}

void Remove(DoublyLinkedList *&head, int pos)
{
if(pos < 1 || head == NULL) return;

DoublyLinkedList *p = head;
if(pos == 1)
{
head = p->next;
head->pre = NULL;
delete p;
return;
}

int cnt = 0;
while(cnt < pos-2 && p->next!=NULL)
{
p = p->next;
cnt++;
}

if(p->next == NULL) return;

DoublyLinkedList *tmp = p->next;
p->next = p->next->next;
p->next->next->pre = p;
delete tmp;
}

int main(void)
{
int a[] = {4,2,6,1,3,5,7};
DoublyLinkedList *head = NULL;
//Insert(head,1,10);
Remove(head,1);
BuildDoublyLinkedList(head,a,sizeof(a)/sizeof(a[0]));
/*Traverse(head);
AddAtHead(head,0);
AddAtTail(head,8);
Remove(head,1);*/
Traverse(head);
MakeEmpty(head);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: