C++ Data Structure

线性表

顺序表

#include<bits/stdc++.h>
using namespace std;

template<typename T>
class SqList {
private:
	int Maxsize;	// 最大容量
	T* elements;	// 元素首地址
	int length;		// 元素个数

public:
	// 创建新的顺序表
	SqList(int maxsize = 10) :Maxsize(maxsize) {
		elements = new T[maxsize];
		length = 0;
	}

	// 获取表长
	void	GetLenth() {
		cout << "表长 = " << length << endl;
	}

	//	判空
	bool IsEmpty() {
		return length == 0;
	}

	// 插入元素
	void InsetElem(T elem, int pos) {
		if (IsEmpty()) {
			elements[length++] = elem;
		}
		else if (pos > length + 1 || pos < 1) {
			cout << "插入位置不合法" << endl;
		}
		else if (length == Maxsize) {
			cout << "该顺序表容量已满,无法插入" << endl;
		}
		else {
			for (int i = length; i >= pos; i--) {
				elements[i] = elements[i - 1];
			}
			elements[pos - 1] = elem;
			length++;
			cout << "成功插入元素" << endl;
		}
	}

	// 删除指定元素
	void DeleteElem(T elem, int pos) {
		if (IsEmpty()) {
			cout << "该顺序表为空,无法删除元素" << endl;
		}
		else if (pos<1 || pos>length) {
			cout << "删除位置不合法,请重试" << endl;
		}
		else {
			if (elements[pos - 1] != elem) {
				cout << "该位置的元素并非所给元素" << endl;
			}
			else {
				for (int i = pos - 1; i < length - 1; i++) {
					elements[i] = elements[i + 1];
				}
				cout << "删除成功" << endl;
				length--;
			}
		}

	}

	// 查找元素并返回第一次出现的位置
	int FindElem(T elem) {
		for (int i = 0; i < length; i++) {
			if (elements[i] == elem) {
				cout << "查找成功" << endl;
				return i + 1;
			}
		}
		cout << "该表不存在该元素" << endl;
		return -1;
	}

	// 打印表内元素
	void Print() {
		for (int i = 0; i < length; i++) {
			cout << elements[i] << ' ';
		}
		cout << endl;
	}
};

int main() {
	int maxlen;
	cin >> maxlen;
	SqList<int> sq(maxlen);

	for (int i = 1; i <=3; i++) {
		sq.InsetElem(i,1);
	}
	sq.Print();

	sq.DeleteElem(2, 2);
	sq.Print();

	sq.GetLenth();
	cout << sq.FindElem(5);

	return 0;
}

链表

单链表

#include<bits/stdc++.h>
using namespace std;

class Node {
public:
	int date;
	Node* next;
};

class LinkList {
public:
	Node* head;	// 头结点
	LinkList() {
		head = new Node;
		head->next = NULL;
	}
	~LinkList() {
		delete head;
	}

	// 头插法创建链表
	void CreateLinkListHead(int n);

	// 尾插法创建链表
	void CreateLinkListBack(int n);

	// 在指定位置插入结点
	void InsertNode(int pos, int elem);

	// 删除某个结点
	void DelNode(Node* p);

	// 查找值为val的结点,返回结点地址
	Node* FindNode(int val);

	// 打印链表
	void PrintLinkList();

};

void LinkList::CreateLinkListHead(int n) {
	while (n--) {
		cout << "请输入date" << endl;
		Node* p = new Node;
		cin >> p->date;
		p->next = head->next;
		head->next = p;
	}
}

void LinkList::CreateLinkListBack(int n) {
	Node* h = head;
	while (n--) {
		cout << "请输入date" << endl;
		Node* p = new Node;
		cin >> p->date;
		p->next = h->next;
		h->next = p;
		h = p;
	}
	//delete h;	这里不能delete因为会删除最后一个结点
}

void LinkList::InsertNode(int pos, int elem) {
	int ind = 0;
	Node* p = new Node;
	Node* h = head;
	while (h->next) {
		ind++;
		if (ind == pos) {
			p->date = elem;
			p->next = h->next;
			h->next = p;
			break;
		}
	}
}

void LinkList::DelNode(Node* p) {
	if (p == NULL) return;
	Node* h = head;
	while (h->next != p) {
		h = h->next;
	}
	h->next = p->next;
	delete h;
}

Node* LinkList::FindNode(int val) {
	Node* p = head->next;
	while (p) {
		if (p->date == val) return p;
		p = p->next;
	}
	delete p;
	return NULL;
}

void LinkList::PrintLinkList() {
	Node* p = head->next;
	while (p) {
		cout << p->date << ' ';
		p = p->next;
	}
	cout << endl;
}

int main() {
	LinkList lt;
	lt.CreateLinkListBack(5);
	lt.PrintLinkList();

	lt.FindNode(3);
	lt.InsertNode(1, 0);
	lt.PrintLinkList();

	return 0;
}

双向循环链表

#include <bits/stdc++.h>

using namespace std;

struct Node
{
    int date;
    Node *next;
    Node *last;
    Node() {}
    Node(int val, Node *last, Node *next)
    {
        this->date = val;
        this->next = next;
        this->last = last;
    }
};

class LinkList
{
private:
    Node *head;
    int cnt;

public:
    LinkList() : cnt(0)
    {
        cout << "构造双链表" << endl;
        head = new Node();
        head->last = head->next = head;
    }

    ~LinkList()
    {
        cout << "析构双链表" << endl;
        // 删除所有结点
        Node *cur = head;
        while (cur)
        {
            Node *p = cur;
            cur = cur->next;
            delete p; // 注意这个放在最后的位置
        }
    }

    // 头插法
    void addHead(int val)
    {
        Node *p = new Node(val, head, head->next);
        head->next->last = p;
        head->next = p;
        cnt++;
    }

    // 尾插法
    void addTail(int val)
    {
        Node *p = new Node(val, head->last, head);
        head->last->next = p;
        head->last = p;
        cnt++;
    }

    // 获取index处的结点
    Node *getNode(int index)
    {
        if (index < 0 || index >= cnt)
            return NULL;
        // 正向查找
        if (index <= cnt / 2)
        {
            int i = 0;
            Node *p = head->next;
            while (i++ < index)
            {
                p = p->next;
            }
            return p;
        }
        // 反向查找
        int j = 0;
        int rindex = cnt - index - 1; // 反向的index
        Node *p = head->last;
        while (j++ < rindex)
        {
            p = p->last;
        }
        return p;
    }

    // 在pos处插入val
    void insertNode(int index, int val)
    {
        if (index == 0)
        {
            addHead(val);
            return;
        }
        Node *p = getNode(index);
        Node *node = new Node(val, p->last, p);
        p->last->next = node;
        p->last = node;
        cnt++;
    }

    // 删除index结点
    void deleteNode(int index)
    {
        if (!head)
            return;
        Node *p = getNode(index);
        p->last->next = p->next;
        p->next->last = p->last;
        delete p;
        cnt--;
    }

    // 删除头结点
    void removeHead(){
        deleteNode(0);
    }

    // 删除尾结点
    void removeTail(){
        deleteNode(cnt-1);
    }

    // 打印双链表
    void print()
    {
        int i = cnt;
        Node *cur = head;
        while (i--)
        {
            cur = cur->next;
            cout << cur->date << ' ';
        }
        cout << endl;
    }
};

int main(){
    LinkList list;
    cout<<"头插法添加头结点"<<endl;
    list.addHead(3);
    list.addHead(4);
    list.addHead(5);
    cout<<"添加成功"<<endl;
    list.print();
    cout<<"尾插法添加尾结点"<<endl;
    list.addTail(2);
    list.addTail(1);
    cout<<"添加成功"<<endl;
    list.print();
    cout<<"删除头结点"<<endl;
    list.removeHead();
    list.print();
    cout<<"删除尾结点"<<endl;
    list.removeTail();
    list.print();
    cout<<"删除第一个结点"<<endl;
    list.deleteNode(1);
    list.print();
    cout<<"在第二个位置插入一个结点2"<<endl;
    list.insertNode(1,2);
    list.print();

    return 0;
}

顺序栈(数组实现)

#include <bits/stdc++.h>
using namespace std;

class Stack
{
private:
    int top;           // 栈顶指针
    unsigned capacity; // 栈的最大容量
    int *data;

    bool is_full()
    {
        return top == capacity - 1;
    }

    bool is_empty()
    {
        return top == -1;
    }

public:
    Stack(unsigned capacity)
    {
        this->capacity = capacity;
        top = -1;
        data = new int[capacity];
    }

    ~Stack()
    {
        delete data;
    }

    // 入栈
    void push(int val)
    {
        if (is_full())
        {
            throw out_of_range("the Stack is full\n");
        }
        data[++top] = val;
    }

    // 出栈
    int pop()
    {
        if (is_empty())
        {
            throw out_of_range("the Stack is empty\n");
        }
        return data[top--];
    }

    // 查看栈顶元素
    int peek()
    {
        if (is_empty())
        {
            throw out_of_range("the Stack is empty");
        }
        return data[top];
    }

    // 判空(在类外可以访问)
    bool Is_Empty()
    {
        return is_empty();
    }
};

int main()
{
    Stack s(10);

    cout << "判空:" << s.Is_Empty() << endl;
    for (int i = 1; i <= 5; i++)
    {
        printf("将%d入栈\n", i);
        s.push(i);
    }

    cout << "判空" << s.Is_Empty() << endl;
    cout << "栈顶元素为:" << s.peek() << endl;
    cout << "出栈\n";
    s.pop();
    cout << "栈顶元素为:" << s.peek() << endl;

    return 0;
}

链栈(链表实现)

#include <bits/stdc++.h>
using namespace std;

struct Node
{
    int val;
    Node *next;
    Node(int x) : val(x), next(NULL) {}
};

class Stack
{
private:
    Node *top; // 栈顶指针

public:
    Stack() : top(nullptr) {}

    ~Stack()
    {
        while (!is_empty())
        {
            pop();
        }
    }

    // 入栈
    void push(int val)
    {
        Node *p = new Node(val);
        p->next = top; // 头插法
        top = p;
    }

    // 出栈
    int pop()
    {
        if (is_empty())
        {
            throw out_of_range("the Stack is empty");
        }
        Node *p = top;
        int val = p->val;
        top = top->next;
        delete p;
        return val;
    }

    // 查看栈顶元素
    int peek()
    {
        if (is_empty())
        {
            throw out_of_range("the Stack is empty");
        }
        return top->val;
    }

    // 判空
    bool is_empty()
    {
        return top == nullptr;
    }
};

int main()
{
    Stack s;

    cout << "判空:" << s.is_empty() << endl;
    for (int i = 1; i <= 5; i++)
    {
        printf("将%d入栈\n", i);
        s.push(i);
    }
    cout << "判空:" << s.is_empty() << endl;
    cout << "栈顶元素为:" << s.peek() << endl;
    cout << "出栈\n";
    s.pop();
    cout << "栈顶元素为:" << s.peek() << endl;
    cout << "析构\n";
    s.~Stack();
    cout << "判空:" << s.is_empty() << endl;

    return 0;
}

STL实现

#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define int ll
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int MOD = 1e9 + 7;
const int N = 2e5 + 2;

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    stack<int> S;

    for (int i = 1; i <= 5; i++)
    {
        S.push(i);
    }
    cout << S.top() << ' ';
    S.pop();
    cout << S.top() << ' ';

    return 0;
}

P1449后缀表达式

#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define int ll
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int MOD = 1e9 + 7;
const int N = 2e5 + 2;

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    stack<int> s;
    char c;
    string ss;
    while (cin >> c, c != '@')
    {
        if ('0' <= c && c <= '9')
        {
            ss += c;
        }
        else if (c == '.')
        {
            s.push(stoll(ss));
            ss.clear();
        }
        else
        {
            int a = s.top();
            s.pop();
            int b = s.top();
            s.pop();

            if (c == '+')
                s.push(a + b);
            else if (c == '-')
                s.push(b - a);
            else if (c == '*')
                s.push(a * b);
            else if (c == '/')
                s.push(b / a);
        }
    }
    cout << s.top() << endl;
    return 0;
}

P1739表达式括号匹配

#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define int ll
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int MOD = 1e9 + 7;
const int N = 2e5 + 2;

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    char c;
    stack<char> s;
    bool f = true;
    while (cin >> c, c != '@')
    {
        if (c == '(')
            s.push(c);
        else if (c == ')')
        {
            if (s.empty())
            {
                f = false;
            }
            else
                s.pop();
        }
    }
    if (f && s.empty())
        puts("YES");
    else
        puts("NO");
    return 0;
}

队列

链式队列

#include <bits/stdc++.h>

using namespace std;

#define ll long long
// #define int ll
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int MOD = 1e9 + 7;
const int N = 2e5 + 2;

template <typename T>
struct node
{
    T data;
    node<T> *next;
};

// 链式队列类
template <typename T>
class Link_Queue
{
protected:               // 设置为 private 也可,protected 用于方便继承
    node<T> *front_node; // 队列头结点指针
    node<T> *back_node;  // 队列尾结点指针

public:
    Link_Queue();                       // 构造函数
    Link_Queue(const Link_Queue<T> &a); // 拷贝构造函数
    bool empty();
    void push(T data);
    void pop();
    void clear();
    const T front();                        // 获取队首元素
    const T back();                         // 获取队尾元素
    void operator=(const Link_Queue<T> &a); // 赋值重载函数
    int size();
    ~Link_Queue(); // 析构函数
};

// 构造函数
template <typename T>
Link_Queue<T>::Link_Queue()
{
    front_node = NULL;
    back_node = NULL;
}
// 拷贝构造函数
template <typename T>
Link_Queue<T>::Link_Queue(const Link_Queue<T> &a)
{
    front_node = NULL;
    back_node = NULL;
    node<T> *cur = a.front_node;
    while (cur)
    {
        push(cur->data);
        cur = cur->next;
    }
}

// 析构函数
template <typename T>
Link_Queue<T>::~Link_Queue()
{
    clear();
}

// 判空
template <typename T>
bool Link_Queue<T>::empty()
{
    if (front_node == NULL)
        return true;
    return false;
}

// 入队
template <typename T>
void Link_Queue<T>::push(T data)
{
    node<T> *p = new node<T>;
    p->data = data;
    p->next = NULL;
    if (back_node == NULL)
        back_node = p; // 处理头结点和尾结点
    else
    {
        back_node->next = p;
        back_node = p;
    }
    if (front_node == NULL)
        front_node = p;
}

// 出队
template <typename T>
void Link_Queue<T>::pop()
{
    if (front_node == NULL)
    {
        cout << "Empty!" << endl;
        return;
    }
    node<T> *p = front_node->next; //  先记录新的头结点再删除
    delete front_node;
    front_node = p;
    if (front_node == NULL)
        back_node = NULL; // 思考为什么需要写这步
}

// 清空队列
template <typename T>
void Link_Queue<T>::clear()
{
    while (front_node != NULL)
    {
        node<T> *p = front_node->next;
        delete front_node;
        front_node = p;
    }
    front_node = NULL;
    back_node = NULL;
}

// 访问队首元素
template <typename T>
const T Link_Queue<T>::front()
{
    if (front_node == NULL)
    {
        cout << "Empty!" << endl;
        return -1;
    }
    return front_node->data;
}

// 访问队尾元素
template <typename T>
const T Link_Queue<T>::back()
{
    if (back_node == NULL)
    {
        cout << "Empty!" << endl;
        return -1;
    }
    return back_node->data;
}

// 操作符重载
template <typename T>
void Link_Queue<T>::operator=(const Link_Queue<T> &a)
{
    clear();
    node<T> *cur = a.front_node;
    while (cur)
    {
        push(cur->data);
        cur = cur->next;
    }
}

// 获取元素个数
template <typename T>
int Link_Queue<T>::size()
{
    int cnt = 0;
    node<T> *p = this->front_node;
    while (p)
    {
        cnt++;
        p = p->next;
    }
    return cnt;
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    Link_Queue<int> q;
    q.push(1);
    cout << q.empty() << endl;
    cout << q.front() << endl;
    cout << q.back() << endl;
    cout << q.size() << endl;
    q.~Link_Queue();
    cout << q.empty() << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值