最近在复习数据结构和算法方面知识,链表是第一次学习的数据结构,虽然简单但写起来还是挺麻烦的。上代码:
#pragma once
#include<iostream>
using namespace std;
//单个节点
template<class Elem> class Node
{
public:
Elem data;
Node<Elem> *next;
Node(const Elem& node,Node *nextNode = NULL)
{
data = node;
next = nextNode;
}
Node(Node *nextNode = NULL) {next = nextNode;}
};
template<class Elem> class LinkedList
{
public:
LinkedList() { head = NULL; }
//插入结点,把结点插入到exitData之前
//1.链表为空,则插入结点为头结点
//2.1.existData不存在,则插入到最后
//3.existData存在
//3.1.existData为头结点
//3.2.existData为中间结点
void insertList(const Elem& existData,const Elem& insertData)
{
Node<Elem> *tempHead,*preNode,*newNode;
tempHead = head;
newNode = new Node<Elem>(insertData);
if (head == NULL)
{
head = newNod