双向链表
双向链表和单链表的区别就在于多了一个前驱;有需要查看单链表的在主页里面查找;
双向链表代码如下:
typedef class Node
{
public:
int data;
Node *next;
Node *pre;
}node;
class doublelist
{
public:
doublelist()
{
head = NULL;
count = 0;
}
~doublelist()
{
}
Node *buyNode(int val,Node *next,Node * pre)
{
Node *p = new Node();
p->data = val;
p->next = next;
p->pre = pre;
return p;
}
void Insert(int pos, int val)
{
if (pos < 0 || pos > count)
{
cout << "the pos is error!" << endl;
return;
}
if (head == NULL)
{
head = buyNode(val, NULL, NULL);
count++;
return;
}
if (pos == 0)
{
Node *s = buyNode(val, head, NULL);
head = s;
}
else
{
Node *p = head;
Node *q = p->next;
while (pos - 1 > 0)
{
p = p->next;
q = q->next;
pos--;
}
Node *s = buyNode(val, q, p);
p->next = s;
}
count++;
}
void Inserthead(int val)
{
Insert(0, val);
}
void Inserttail(int val)
{
Insert(count, val);
}
void Delete(int pos)
{
if (pos > count || pos < 0)
{
cout << "the pos is error!" << endl;
return;
}
Node *p = head;
Node *q = p->next;
if (pos == 0)
{
free(p);
head = q;
}
else if (pos == 1)
{
p->next = q->next;
}
else
{
while (pos - 1 > 0)
{
p = p->next;
pos--;
}
p->pre->next = p->next;
}
count--;
}
void Deletehead()
{
Delete(0);
}
void Deletetail()
{
Delete(count);
}
int getcount()
{
return count;
}
void show()
{
Node *p = head;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
private:
Node *head;
int count;
};
int main()
{
doublelist d;
for (int i = 0; i < 10; i++)
{
d.Inserttail(i);
}
d.show();
d.Delete(10);
d.show();
return 0;
}
循环链表
循环链表的和单链表的区别在与循环链表首位相连。
循环链表的代码如下:
class Node
{
public:
Node *next;
int data;
};
class CycleList
{
public:
CycleList()
{
head = NULL;
count = 0;
}
~CycleList()
{
}
Node *buyNode(int val,Node *next)
{
Node* p = new Node();
p->data = val;
if (next == NULL)
{
p->next = p;
}
else
{
p->next = next;
}
return p;
}
void Insert(int pos, int val)
{
if (pos < 0 || pos > count)
{
cout << "the pos is error!" << endl;
return;
}
if (head == NULL)
{
head = buyNode(val, NULL);
count++;
return;
}
Node *p = head;
if (pos == 0)
{
pos = count;
while (pos - 1> 0)
{
p = p->next;
pos--;
}
Node *s = buyNode(val, p->next);
p->next = s;
head = s;
}
else
{
while (pos - 2 > 0)
{
p = p->next;
pos--;
}
Node *s = buyNode(val, p->next);
p->next = s;
}
count++;
}
void Inserthead(int val)
{
Insert(0, val);
}
void Inserttail(int val)
{
Insert(count, val);
}
void Delete(int pos)
{
if (pos < 0 || pos > count)
{
cout << "the pos is error" << endl;
return;
}
Node *p = head;
Node *q = p->next;
if (pos == 1)
{
free(head);
head = q;
}
else
{
while (pos - 2 > 0)
{
p = p->next;
q = q->next;
pos--;
}
p->next = q->next;
free(q);
}
}
void Deletehead()
{
Delete(0);
}
void Deletetail()
{
Delete(count);
}
void show()
{
Node *p = head;
Node *q = p;
while (p->next != q)
{
cout << p->data << " ";
p = p->next;
}
cout << p->data << endl;
}
private:
Node *head;
int count;
};
int main()
{
CycleList c;
for (int i = 0; i < 3; i++)
{
c.Inserthead(i);
}
c.Insert(2, 10);
c.show();
c.Deletehead();
c.show();
return 0;
}