链表操作
作者:
ternua
,
2024-08-26 22:13:01
,
所有人可见
,
阅读 1
存档链表
#include <bits/stdc++.h>
#include <iostream>
//链表的构造插入查找输出
using namespace std;
//链表节点定义
struct Node{
int val;
Node *next;
Node(int x) : val(x),next(NULL){};
};
//头插法建立单链表
Node* CreateListByHead(int arr[],int n){
Node* head = NULL;
for(int i = 0;i<n;i++){
Node *node = new Node(arr[i]);
if(head == NULL) head = node;
else
{
node->next = head;
head = node;
}
}
}
//带虚拟头结点的头插法
Node* CreateListwithHead(int arr[],int n)
{
//创建虚拟头结点
Node *dummy = new Node(-1);
for(int i = 0;i<n;i++){
//创建新节点
Node *node = new Node(arr[i]);
node->next = dummy->next;
dummy->next = node;
}
return dummy->next;
}
//尾插法建立单链表
Node* CreateListBytail(int arr[],int n)
{
Node *head = nullptr;
Node *tail = nullptr;
for(int i = 0;i<n;i++){
//创建新节点
Node *node = new Node(arr[i]);
//如果链表为空
if (head == nullptr)
{
head = node;
tail = node;
}
else
{
tail->next = node;
tail = node;
}
}
//带虚拟头结点的尾插法
Node* CreateListWithtail(int arr[],int n)
{
Node *dummy = new Node(-1);
Node *tail = dummy;
for(int i = 0;i<n;i++)
{
//创建节点
Node *node = new Node(arr[i]);
tail->next = node;
tail = node;
}
return dummy->next;
}
//插入
Node *insertNode(Node *head,int index,int x)
{
Node *p = head;
Node *newnode = new Node(x);
for(int i = 0;i<index-1;i++)
p = p->next;
newnode->next = p->next;
p->next = newnode;
}
//删除
Node *deleteNode(Node *head,int index,int x)
{
Node *p = head;
for(int i = 0;i<index-1;i++)
p = p->next;
x = p->next->val;
p->next = p->next->next;
}
//查找,索引查找
Node *getNodebyindex(Node *head,int i)
{
Node *p = head;
for(;i = 0;i--)
{
p = p->next;
return p;
}
}
//查找,值查找
Node *getNodebyval(Node *head,int e)
{
for(Node *p = head;p;p = p->next)
{
if(p->val == e);
return p;
}
}
//遍历输出
void print(Node *head)
{
for (Node *p = head;p;p = p->next)
{
cout<<p->val<<' ';
cout<<endl;
}
}
int main(){
int a[] = {[0]:1,[1]:1,[2]:5,[3]:1};
int n = sizeof(a) / sizaof(int);
Node *head = CreateListWithtail(a,n);
print(head);
insertNode(head, 2, 0);
print(head);
return 0;
}