链表节点(其中info 表示节点信息,next是下一个节点引用,其中info可以通过template<class T> 实现泛型链表)
#pragma once
class IntSSLNode
{
public:
IntSSLNode()
{
next = 0;
info = 0;
}
IntSSLNode(int info, IntSSLNode* in = 0)
{
this->info = info;
next = in;
}
int info;
IntSSLNode* next;
};
链表类
#pragma once
#include "IntSSLNode.h"
class IntSSList
{
public:
IntSSList()
{
head = tail = 0;
}
~IntSSList();
int isEmpty()
{
return head == 0;
}
void addToHead(int);
void addTotail(int);
int deleteFromHead();
int deleteFromTail();
void deleteNode(int);
bool isInList(int) const;
private:
IntSSLNode* head, * tail;
};
#include<iostream>
#include "IntSSList.h"
IntSSList::~IntSSList() {
for (IntSSLNode* p; !isEmpty();)
{
p = head->next;
delete head;
head = p;
}
}
void IntSSList::addToHead(int el)
{
head = new IntSSLNode(el, head);
if (tail == 0)
{
tail = head;
}
}
void IntSSList::addTotail(int el)
{
if (tail != 0)
{
tail->next = new IntSSLNode(el);
tail = tail->next;
}
else
{
head = tail = new IntSSLNode(el);
}
}
int IntSSList::deleteFromHead()
{
int el = head->info;
IntSSLNode* temp = head;
if (head == tail)
{
head = tail = 0;
}
else
{
head = head->next;
}
delete temp;
return el;
}
int IntSSList::deleteFromTail()
{
int el = tail->info;
if (head == tail)
{
delete head;
head = tail = 0;
}
else
{
IntSSLNode* tmp;
for (tmp = head; tmp->next != tail; tmp = tmp->next);
delete tail;
tail = tmp;
tail->next = 0;
}
return el;
}
void IntSSList::deleteNode(int el)
{
if (head != 0)
if (head == tail && el == head->info) {
delete head;
head = tail = 0;
}
else if (el == head->info)
{
IntSSLNode* tmp = head;
head = head->next;
delete tmp;
}
else
{
IntSSLNode* pred,* tmp;
for (pred=head,tmp=head->next;
tmp!=0 && !(tmp->info == el);
pred=pred->next,tmp=tmp->next);
if (tmp != 0)
{
pred->next=tmp->next; //三个节点删除中间一个节点,需要把上一个节点和下一个节点链接起来。
if (tmp == tail) //当删除的节点是末端节点则新的末端节点是上一个节点
{
tail = pred;
}
delete tmp;
}
}
}
bool IntSSList::isInList(int el) const{
IntSSLNode* tmp;
for (tmp = head; tmp != 0 && !(tmp->info == el); tmp = tmp->next);
return tmp != 0;
}
测试
int main()
{
IntSSList* list = new IntSSList();
list->addTotail(1);
list->addTotail(2);
list->addTotail(3);
list->addTotail(4);
list->addToHead(5);
//int i = list->deleteFromHead();
//i = list->deleteFromTail();
list->deleteNode(3);
}
来源:https://www.cnblogs.com/ms_senda/p/11312093.html