暑假在学习数据结构,重新接触了一下C++的链表,相比于数组,链表有很多方便的地方,并且在数据结构这门课中会频繁出现,所以十分重要。
每一个结点有data部分和指针部分,把它们一个接一个连接起来就形成了链表。
相对于数组,链表的长度可以一开始不确定,并且data部分可以有多种类型,例如同时有char类型和int类型。
1.链表结构
2.在链表末尾插入结点
3.打印链表
4.删除链表
5.反转链表
6.源码
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
//在链表末插入结点
void Insert(Node* head, int n)
{
cout << "添加第" << ++head->data << "个元素!" << endl;
Node* temp;
temp = new Node;
temp->data = n;
if (head->next == NULL)
{
head->next = temp;
head = temp;
head->next = NULL;
return;
}
while (head->next != NULL)
{
head = head->next;
}
head->next = temp;
head = temp;
head->next = NULL;
}
//打印数据
void Print(Node* head)
{
cout << "共有" << head->data << "个结点:\t";
head = head->next;
while (head != NULL)
{
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
//删除结点
void Delete(Node* head, int n)
{
if (n<1 || n>head->data)
return;
cout << "删除第" << n << "个元素" << endl;
head->data--;
for (int i = 0; i < n - 1; i++)
{
head = head->next;
}
Node* temp1 = head->next;
head->next = temp1->next;
delete temp1;
}
//反转链表
void Reverse(Node* head)
{
if (head->next == NULL || head->next->next == NULL)
{
return; /*链表为空或只有一个元素则直接返回*/
}
Node* t = NULL;
Node* p = head->next;
Node* q = head->next->next;
while (q != NULL)
{
t = q->next;
q->next = p;
p = q;
q = t;
}
/*此时q指向原始链表最后一个元素,也是逆转后的链表的表头元素*/
head->next->next = NULL; /*设置链表尾*/
head->next = p; /*调整链表头*/
}
int main()
{
Node* head = new Node;//创建头结点,其中data部分记录结点个数
head->data = 0;//用来记录结点个数
head->next = NULL;
Insert(head, 1);
Insert(head, 2);
Insert(head, 3);
Print(head);
Delete(head, 3);
Print(head);
Reverse(head);
Print(head);
delete head;
}
注意:传入参数的时候若加了引用&,会改变head头指针的指向,链表的操作要注意头指针的移动