與單連結清單相比,每個單元加上前向指針
#include <tchar.h>
#include <iostream>
using namespace std;
typedef struct student{
int data;
struct student * next;
struct student * pre;
} node;
node* create()
{
node *head, *p, *s;
int x, cycle = 1;
head = (node *)malloc(sizeof(node));
p = head;
while(cycle)
{
cout << "please input the data: ";
cin >> x;
cout << endl;
if( x != 0)
{
s = (node *)malloc(sizeof(node));
s->data = x;
p->next = s;
s->pre = p;
p = s;
}
else
{
cycle = 0;
}
}
p->next = NULL;
head = head->next;
head->pre = NULL;
return head;
}
int length(node *head)
{
int n = 0;
node *p;
p = head;
while (p != NULL)
{
p = p->next;
n++;
}
return n;
}
void print(node *head)
{
int n;
node *p;
p = head;
n = length(head);
cout << "There is " << n << " data in list\n" << endl;
while(p->next != NULL)
{
cout << p->data << " -> ";
p = p->next;
}
cout << p->data << endl;
while(p->pre !=NULL)
{
cout << p->data << " -> ";
p = p->pre;
}
cout << p->data << endl;
}
int _tmain(int argc, _TCHAR * argv[])
{
node *head, *temp;
head = create();
print(head);
return 0;
}