1.初始化链表:
在定义初始化链表时,重新定义了一个头结点(Node* head = new Node),但已经在class LinkList时,创建过head,故再次创建会出现冲突
2.头插法创建链表:
使用头插法的时间复杂度是O(1),而使用尾插法,时间复杂度是O(n)。因为头插法只需要一直从head找即可,但尾插法则需要遍历。下面给出头插法的思维构图:
3.插入节点:
只需使用一个Node* tmp来记录当前结点和后继节点的地址,再新申请一个将要插入的结点Node* Insert_Node = new Node;即可,无需再次申请其他多余结点。
4.删除结点:
删除操作相对简单,只是注意理解,链表只能找到后继结点。
LinkLishhead.h
#include<iostream>
using namespace std;
//想要创建链表,必须得先创建结点啊
struct Node {
int val;
Node* next;
};
class LinkList
{
public:
Node* head;
LinkList();
void CreateList(int n);
void Insert(int i, int e);
void Delete(int j);
void Display();
void GetLength();
};
//初始化链表
LinkList::LinkList()
{
//Node* head = new Node;//已经在class LinkList时定义过Node* head , 初始化链表的时候,无需重新定义,只需要为head分配内存即可
head = new Node;
head->val = 0;
head->next = NULL;
}
void LinkList::Display() {
Node* tmp;
tmp = head->next;
while (tmp) {
cout << tmp->val << " ";
tmp = tmp->next;
}
}
void LinkList::CreateList(int n) { // 头插法创建链表
for (int i = 0; i < n; i++) {
Node* tmp = new Node;
cout << "please tap in your Node val : ";
cin >> tmp->val;
tmp->next = head->next;
head->next = tmp;
}
};
void LinkList::Insert(int i , int e) {
Node* Insert_Node = new Node;
Insert_Node->val = e;
Node* tmp;
tmp = head;
int j = 0;
while (j < i) {
tmp = tmp->next;
j++;
};
Insert_Node->next = tmp->next;
tmp->next = Insert_Node;
};
void LinkList::Delete(int i) {
Node* pos;//用于记录要删除的位置
pos = head;
int j = 0;
if (i == 1) {
pos->next = pos->next->next;
//delete(pos->next);
//pos->next = NULL;
}
else
{
while (j < i && i > 1) {
pos = pos->next;//pos最后可以找到第i个位置
j++;
if (j == i - 1) {
break;
};
};
pos->next = pos->next->next;
//delete(pos->next);
//pos->next = NULL;
}
};
void LinkList::GetLength() {
Node* tmp;
tmp = head;
int j = 0;
while (tmp) {
tmp = tmp->next;
j++;
}
cout << "The length of this LinkList is :" << j - 1;
}
LinkList.cpp
#include<iostream>
#include"LinkListhead.h"
using namespace std;
void main() {
int user_num;
int Insert_pos;
int Insert_num;
int Delete_pos;
cout << "please tap the length of your LinkList : ";
cin >> user_num;
LinkList list1;
//头插法创建链表
list1.CreateList(user_num);
cout << "the number of each Node : ";
list1.Display();
system("pause");
//插入结点
cout << "please tap the pos you wanna Insert : ";
cin >> Insert_pos;
cout << "please tap the number you wanna Insert:";
cin >> Insert_num;
list1.Insert(Insert_pos, Insert_num);
cout << "the number of each Node : ";
list1.Display();
system("pause");
//删除结点
cout << "please tap the pos your wanna delete :";
cin >> Delete_pos;
list1.Delete(Delete_pos);
cout << "the LinkList after Deleting : ";
list1.Display();
system("pause");
//获得链表长度
list1.GetLength();
system("pause");
}