使用头文件定义两个类,IntSLNode是表中的节点,另一个是IntSLList用于访问链表
IntSLList.h
#ifndef INT_LINKED_LIST
#define INT_LINKED_LIST
class IntSLNode {
public:
IntSLNode() {
next = 0;
}
IntSLNode(int e1, IntSLNode*ptr = 0) {
info = e1;
next = ptr;
}
int info;
IntSLNode*next;
};
class IntSLList {
public:
IntSLList() {
head = tail = 0;
}
~IntSLList();
int isEmpty() {
return head == 0;
}
void addToHead(int);
void addToTail(int);
//删除头节点并且返回其数值
int deleteFromHead();
//删除尾节点并且返回其数值
int deleteFromTail();
void deleteNode(int);
bool isInList(int) const;
private:
IntSLNode*head, *tail;
};
#endif //
IntSLList.cpp
// c++_test.cpp : 定义控制台应用程序的入口点。
//
#include<iostream>
#include"IntSLList.h"
//删除链表
IntSLList::~IntSLList() {
for (IntSLNode*p; !isEmpty();) {
p = head->next;
delete p;
head = p;
}
}
//添加元素到头部
void IntSLList::addToHead(int e1) {
head = new IntSLNode(e1, head);
if (tail == 0) {
tail = head;
}
}
//添加元素到尾部
void IntSLList::addToTail(int e1) {
if (tail != 0) { //如果链表非空
tail->next = new IntSLNode(e1);
tail = tail->next;
}
else {
head = tail = new IntSLNode(e1);
}
}
//从链表头部开始删除数据
int IntSLList::deleteFromHead() {
int e1 = head->info;
IntSLNode*tmp = head;
if (head == tail) { //如果链表中只有一个节点
head = tail = 0;
}
else {
head = head->next;
}
delete tmp;
return e1;
}
//从链表尾部开始删除数据
int IntSLList::deleteFromTail() {
int e1 = tail->info;
if (head == tail) {
delete head;
head = tail = 0;
}
else {
IntSLNode*tmp;
for (tmp = head; tmp->next != tail; tmp = tmp->next);
delete tail;
tail = tmp;
tail->next = 0;
}
return e1;
}
//删除特定节点
void IntSLList::deleteNode(int e1) {
if(head!=0)
if (head == tail&&e1 == head->info) {
delete head;
head = tail = 0;
}
else if (e1 == head->info) {
IntSLNode*tmp = head;
head = head->next;
delete tmp;
}
else {
IntSLNode*pred, *tmp;
for (pred = head, tmp = head->next; tmp != 0 &&
!(tmp->info = e1); pred = pred->next, tmp = tmp->next);
if (tmp != 0) {
pred->next = tmp->next;
if (tmp == tail)
tail = pred;
delete tmp;
}
}
}
bool IntSLList::isInList(int e1) const {
IntSLNode*tmp;
for (tmp = head; tmp != 0 && !(tmp->info == e1); tmp = tmp->next);
return tmp != 0;
}