最近在复习数据结构和算法方面知识,链表是第一次学习的数据结构,虽然简单但写起来还是挺麻烦的。上代码:
#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 = newNode;
}
else if(tempHead->data == existData) //头结点为existData
{
newNode->next = tempHead;
head = newNode;
}
else //头结点为中间结点
{
while (tempHead != NULL)
{
preNode = tempHead;
//存在则插入到existData前面并返回
if (tempHead->data == existData)
{
preNode->next = newNode;
newNode->next = tempHead;
return ;
}
tempHead = tempHead->next;
}
//运行到这里说明不存在existData,则插到最后
preNode->next = newNode;
newNode->next = NULL;
}
}
//删除existData结点
//1.链表为空,直接返回
//2.existData为头结点
//3.existData为除头结点之外结点
//4.existData不存在
bool deleteList(const Elem& existData)
{
Node<Elem> *tempHead,preNode;
tempHead = head;
if (tempHead == NULL)
{
return false;
}
if (tempHead->data == existData) //删除头结点
{
head = NULL;
delete tempHead;
}
else
{
while (tempHead != NULL)
{
preNode = tempHead;
if (tempHead->data == existData)
{
preNode.next = tempHead->next;
delete tempHead;
}
tempHead = tempHead->next;
}
}
return true;
}
//得到链表中第几个数的值
Elem getNElem(int i)
{
Node<Elem> *tempHead = head;
int count = 1;
while (tempHead != NULL)
{
if (count == i)
{
return tempHead->data;
}
count++;
tempHead = tempHead->next;
}
return -1;
}
void outputList()
{
Node<Elem> *temp = head;
while (temp != NULL)
{
cout<<temp->data<<'\t';
temp = temp->next;
}
cout<<endl;
}
private:
Node<Elem> *head;
};
int main()
{
int n;
cout<<"Input the length of the linkedlist:";
cin>>n;
LinkedList<int> linkedList;
for (int i = 0;i < n;i++)
{
linkedList.insertList(i,i);
}
linkedList.outputList();
return 0;
}