数据结构-双向列表
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* prev;
struct Node* Next;
}
struct Node* head;
struct Node* GetNewNode(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 = GetNewNode(int x);
if(head == NULL)
{
head = newNode;
return;
}
head->prev = newNode;
newNode->next = head;
head = newNode;
}
//尾插法
void InsertAtTail(int x)
{
struct Node* newNode = GetNewNode(x);
struct Node* temp = head;
if(head == NULL)
{
head = newNode;
return;
}
while(temp->next != NULL) temp = temp->next;
temp->next = newNode;
newNode->prev = temp;
}
//正向输出
void Print()
{
struct Node* temp = head;
printf("Forward: ");
while(temp != NULL)
{
printf("%d",temp->data);
temp = temp->next;
}
printf("\n");
}
//反向输出
void ReversePrint()
{
struct Node* temp = head;
if(temp == NULL) return;
while(temp->next != NULL)
{
temp = temp ->next;
}
printf("Reverse: ");
while(temp != NULL)
{
printf("%d ",temp->data);
temp = temp->prev;
}
printf("\n");
}
int main()
{
head = NULL;
InsertAtTail(2);Print();ReversePrint();
InsertAtTail(4);Print();ReversePrint();
InsertAtHead(6);Print();ReversePrint();
InsertAtTail(8);Print();ReversePrint();
}