#include<iostream>
using namespace std;
struct node //节点名为node
{
int data;
node* next;
node() : data(0),next(nullptr) {} //构造函数
node(int x):data(x),next(nullptr){} // NULL容易引起二义性,nullptr更好一点
node(int x, node* n) : data(x), next(n) {}
};
node* createlist() //创建长度为n的链表
{
node* head = new node(); //创建空的头节点,此后一直认为头节点是空的
node* p = head; //创建指针指向头节点
int n = 0; //n为要输入的节点个数
cout << "请输入要创建的列表长度" << endl;
cin >> n;
cout << "请输入节点数值" << endl;
for (int i = 0; i < n; i++)//用for循环输入节点的数,建立链表
{
int x = 0;
cin >> x;
node* newnode = new node(x);
head->next = newnode;
head = head->next;
}
head = p; // 输入到此结束
return head;
}
int length(node*h) //获取链表长度
{
int count = 0;
while (h->next!=nullptr)
{
h = h->next;
count++;
}
return count;
}
void insert(node*h,int x, int y) //在元素前插入y
{
node* newnode = new node(y);
node* curr = h;
while (curr->next)
{
if (curr->next->data == x)
{
newnode->next = curr->next;
break;
}
curr = curr->next;
}
curr->next = newnode;
}
void append(node*h,int x) //在头指针为h的链表的结尾插入新节点,元素为x
{
node* newp = new node(x);
if (h->next == nullptr)
h->next = newp;
else
{
while (h->next != nullptr)
h = h->next;
h->next = newp;
}
}
void remove_x(node* h, int x) //删掉第一个值为x的元素
{
node* de = h ; // 暂存被删除节点,用于释放其占用的内存
if (h == nullptr) // 链表为空
return;
while (h->next->data != x)
h = h->next;
de = h->next;
h->next = h->next->next;
if(de!=nullptr)
delete de;
}
void print(node* h) //打印链表,参数为某链表的头指针,操作不改变实参
{
node* n = h->next; // 因为带头节点,因此需要从head->next开始遍历链表
if (n == nullptr) //若是空链表,输出 NULL
cout << "NULL" << endl;
else
{
while (n != nullptr)
{
cout << n->data<<' ';
n = n->next;
}
cout << endl;
}
}
int main()
{
node* head = createlist();
insert(head, 4, 27);
print(head);
}
C++ 链表 基本操作
最新推荐文章于 2022-11-10 11:42:35 发布