双循环链表
#include<bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <vector>
using namespace std;
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node*pre;
struct node*next;
}linkNode,*linkList;
//链表初始化
linkList initLinkList()
{
linkList head=(linkList)malloc(sizeof(linkNode));
if(!head)
{
printf("动态内存分配失败!\n");
exit(0);
}
head->next=head;
head->pre=head;
printf("链表初始化成功!\n");
return head;
}
//建立结点
linkList createNode(int val)
{
linkList head=(linkList)malloc(sizeof(linkNode));
head->data = val;
head->pre = nullptr;
head->next = nullptr;
return head;
}
//尾插法
void insertLinkListByNext(linkList l,int x)
{
linkList newNode = createNode(x);
linkList lastNode = l;
while(lastNode->next != l)
{
lastNode = lastNode->next;
}
l->pre = newNode;
newNode->next = l;
lastNode->next = newNode;
newNode->pre = lastNode;
}
//头插法
void insertNodeByHead(linkList headNode,int data)
{
linkList newNode = createNode(data);
newNode->pre = headNode;
newNode->next = headNode->next;
headNode->next->pre = newNode;
headNode->next = newNode;
}
//正序输出
void printList(linkList l)
{
linkList p = l->next;
while(p != l)
{
printf("%d",p->data);
p = p->next;
}
printf("\n");
}
//逆序输出
void printList_reverse(linkList l)
{
linkList p = l->pre;
while(p != l)
{
printf("%d",p->data);
p = p->pre;
}
printf("\n");
}
//查找指定元素
void searchElement(linkList l,int x)
{
linkList posNode = l->next;
linkList posNodeprior = l;
while(posNode->data != x)
{
posNodeprior = posNode;
posNode = posNodeprior->next;
if(posNode == l)
{
printf("不存在元素!\n");
return ;
}
}
printf("该元素存在!\n");
}
//查找指定元素并更改
void modifyElement(linkList l,int x,int elem)
{
linkList posNode = l->next;
linkList posNodeprior = l;
while(posNode->data != x)
{
posNodeprior = posNode;
posNode = posNodeprior->next;
if(posNode == l)
{
printf("不存在元素!\n");
}
}
posNode->data = elem;
printf("修改成功!\n");
}
//删除指定元素
void Specify(linkList headNode,int posData)
{
linkList posNode = headNode->next;
linkList posNodeprior = headNode;
while(posNode->data != posData)
{
posNodeprior = posNode;
posNode = posNodeprior->next;
if(posNode == headNode)
{
printf("不存在指定位置,无法删除!\n");
return;
}
}
posNodeprior->next = posNode->next;
posNode->next->pre = posNodeprior;
free(posNode);
}
int main()
{
linkList head = initLinkList();
insertLinkListByNext(head,1);
insertLinkListByNext(head,2);
insertLinkListByNext(head,4);
insertLinkListByNext(head,3);
insertLinkListByNext(head,5);
searchElement(head,0);
printList(head);
printList_reverse(head);
linkList head2 = initLinkList();
insertNodeByHead(head2,7);
insertNodeByHead(head2,8);
insertNodeByHead(head2,9);
printList(head2);
printList_reverse(head2);
return 0;
}
保持好奇心!