单链表有next指针,在查询下一个结点的时间复杂度为O(1),但在查询上一个结点时就会很麻烦,因为每次只能从头指针head开始遍历查找。双向链表就克服了这个缺点。
双向链表定义:双向链表是在单链表的每个结点中,再设置一个指向其前驱结点的指针域。所以双向链表的每个结点都有两个指针域,分别指向前后结点。
双向链表特点:
1.每次在插入或删除某个节点时, 需要处理四个节点的引用, 而不是两个. 实现起来要困难些;
2.相对于单向链表, 必然占用内存空间更大一些;
3.既可以从头遍历到尾, 又可以从尾遍历到头。
-定义结构体-
typedef struct node{
int data;
struct node *pre;
struct node *next;
}Node,*linklist;
-初始化链表-
Node *CreatNode(Node *head)
{
head=(Node*)malloc(sizeof(Node));
if(head == NULL)
{
printf("malloc error!\r\n");
return NULL;
}
head->pre=NULL;
head->next=NULL;
return head;
}
-建立链表-
Node* CreatList(Node * head,int length)
{
if (length == 1)
{
return( head = CreatNode(head));
}
else
{
head = CreatNode(head);
Node * list=head;
for (int i=1; i<length; i++)
{
Node * body=(Node*)malloc(sizeof(Node));
body->pre=NULL;
body->next=NULL;
body->data=rand()%MAX;
list->next=body;
body->pre=list;
list=list->next;
}
}
return head;
}
-双向链表的插入-
双向链表的指针较多,插入时要调整的指针也就更多
例如要将s结点插入在链表的p和第p -> next中间,需要以下四步:
1.把p赋值给s的前驱
2.把p -> next赋值给s的后继
3.把s赋值给p ->next的前驱
4.把s赋值给p的后继
void InsertElem( linklist head , int data ){
linklist tmpHead = head; // 创建一个临时的头结点指针
if( tmpHead->next == NULL ){
/* 当双向链表只有一个头结点时 */
linklist addition = (linklist)malloc( sizeof(linklist) );
assert( addition != NULL );
addition -> data = data;
addition -> next = tmpHead->next;
tmpHead -> next = addition;
addition -> front = tmpHead;
}
else{
/* 当双向链表不只一个头结点时 */
linklist addition = (pElem)malloc( sizeof(linklist) );
assert( addition != NULL );
addition -> data = data;
tmpHead -> next->front = addition;
addition -> front = tmpHead;
addition -> next = tmpHead->next;
tmpHead -> next = addtion;
}
}