c++双向链表相关函数及其代码
时间: 2024-06-12 12:08:01 浏览: 69
双向链表是一种常见的数据结构,它比单向链表更加灵活,因为它可以从前向后遍历,也可以从后向前遍历。下面是双向链表的相关函数及其代码实现。
1. 创建双向链表
```C
typedef struct Node{
int data;
struct Node *prev;
struct Node *next;
}Node, *List;
List createList(){
List head = (List)malloc(sizeof(Node));
head->prev = NULL;
head->next = NULL;
return head;
}
```
2. 在双向链表中插入节点
```C
void insert(List head, int data, int position){
Node *p = head;
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
int i = 0;
while(p->next && i < position){
p = p->next;
i++;
}
if(i != position){
printf("Position is not valid!\n");
return;
}
newNode->prev = p;
newNode->next = p->next;
if(p->next){
p->next->prev = newNode;
}
p->next = newNode;
}
```
3. 删除双向链表中的节点
```C
void delete(List head, int position){
Node *p = head;
int i = 0;
while(p->next && i < position){
p = p->next;
i++;
}
if(i != position){
printf("Position is not valid!\n");
return;
}
p->prev->next = p->next;
if(p->next){
p->next->prev = p->prev;
}
free(p);
}
```
4. 修改双向链表中的节点
```C
void update(List head, int position, int data){
Node *p = head;
int i = 0;
while(p->next && i < position){
p = p->next;
i++;
}
if(i != position){
printf("Position is not valid!\n");
return;
}
p->data = data;
}
```
5. 查找双向链表中的节点
```C
Node* search(List head, int data){
Node *p = head->next;
while(p){
if(p->data == data){
return p;
}
p = p->next;
}
return NULL;
}
```
6. 遍历双向链表
```C
void traverse(List head){
Node *p = head->next;
while(p){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
```
以上就是双向链表的相关函数及其代码实现。
阅读全文