具体实现代码如下:
#include<stdio.h>
#include<malloc.h>
using namespace std;
typedef struct DNode{//双链表
int data;
struct DNode *prior;
struct DNode *next;
}DNode;
void CreatelistR(DNode *&head,int arr[],int n);//尾插法创建带头结点的单向链表
void ShowList(DNode *head);
DNode *searchNode(DNode *head,int x);//查找值为x的节点并返回
int insertNode(DNode *&head,int p,int x);//在p位置插入
int deleteNode(DNode *head,int p); //删除第p个位置的节点
int main(){
DNode *head = nullptr;
int arr[] = {123,56,7,867,132,9,45,0,314};
CreatelistR(head,arr,sizeof(arr)/sizeof(arr[0]));
ShowList(head);
puts("请输入查找结点的值:");
int n;
scanf("%d",&n);
DNode *p = searchNode(head,n);
if(p != nullptr)
printf("%d\n",p->data);
puts("请输入插入结点的位置和值:");
int node;
scanf("%d%d",&n,&node);
insertNode(head,n,node);
ShowList(head);
puts("请输入删除结点:");
scanf("%d",&n);
deleteNode(head,n);
ShowList(head);
return 0;
}
int insertNode(DNode *&head,int p,int x){
if(p < 1)
return 0;
if(head == nullptr){
head = (DNode *)malloc(sizeof(DNode));
head->prior = nullptr;
head->next = nullptr;
}
DNode *pre = head;
int i = 1;
while(i < p && pre->next != nullptr){
pre = pre->next;
i++;
}
DNode *node = (DNode *)malloc(sizeof(DNode));
node->data = x;
node->next = pre->next;
node->prior = pre;
if(pre->next != nullptr)
pre->next->prior = node;
pre->next = node;
return 1;
}
int deleteNode(DNode *head,int p){
if(p < 1)
return 0;
if(head == nullptr || head->next == nullptr)
return 0;
DNode *pre = head;
int i = 0;
while(i < p-1 && pre->next != nullptr){
pre = pre->next;
i++;
}
if(pre->next == nullptr)
return 0;
DNode *q = pre->next;
pre->next = q->next;
if(q->next != nullptr)
q->next->prior = pre;
free(q);
return 1;
}
void CreatelistR(DNode *&head,int arr[],int n)//尾插法
{
if(arr == nullptr || n < 0)
return;
head = (DNode *)malloc(sizeof(DNode));
head->prior = nullptr;
head->next = nullptr;
DNode *temp = head;
for(int i=0;i<n;i++)
{
DNode *node = (DNode *)malloc(sizeof(DNode));
node->data = arr[i];
node->prior = temp;
node->next = nullptr;
temp->next = node;
temp = node;
}
}
DNode *searchNode(DNode *head,int x){
if(head == nullptr || head->next == nullptr)
return nullptr;
/*
while(head->next != nullptr){
if(head->next->data == x)
return head->next;
head = head->next;
}
*/
DNode *p = head->next;
while(p != nullptr){
if(p->data == x)
return p;
p = p->next;
}
return nullptr;
}
void ShowList(DNode *head){
if(head == nullptr)
return;
while(head->next != nullptr)
{
printf("%d ",head->next->data);
head = head->next;
}
puts("");
puts("");
}
运行结果如下: