Double linked list
优点
普通的链表无法查看上一个,这个可以查看上一个,那么删除结点,反转链表等会带来便利。
缺点
链表构建更为复杂一点,内存所需要更大
头插,打印(正加反)
#include<stdlib.h>
#include<stdio.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
} ;
struct Node* head;
struct Node* GestNewNode(int x)
{
struct Node* newNode =
(struct Node* )malloc(sizeof(struct Node));
newNode->data = x;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
void InsertAtHead(int x)//头插
{
struct Node* newNode = GestNewNode(x);
if (head == NULL)//如果是空表
{
head = newNode;
return;
}
head->prev = newNode;
newNode->next = head;
head = newNode;
}
void print()
{
struct Node* temp = head;
while (temp != NULL)
{
printf(" %d", temp->data);
temp = temp->next;
}
printf("\n");
}
void Reverseprint() {
struct Node* temp = head;
//going to last Node
while (temp->next != NULL)
{
temp = temp->next;
}
printf("Reverse:");
while (temp != NULL)
{
printf(" %d", temp->data);
temp = temp->prev;
}
printf("\n");
}
int main(void)
{
head = NULL;
InsertAtHead(2);
InsertAtHead(4);
print();//4 2
Reverseprint();//Reverse: 2 4
return 0;
}