双链表的部分基本操作(声明、建表、插入、删除)

双链表声明:

typedef struct DNode {
	ElemType data;
	struct DNode* prior;
	struct DNode* next;
} DLinkNode;

插入结点(在p结点后插入s结点):

p->next = s->next;
p->next->prior = s;
//以下两条可以交换
p->next = s;
s->prior = p;

删除结点(删除p的后继结点q):

p->next = q->next;
q->next->prior = p;

建立双链表(头插法):

   

void CreateListF(DLinkNode*& L, ElemType a[], int n) {
	DLinkNode* s;
	L = (DLinkNode*)malloc(sizeof(DLinkNode));
	L->next = L->prior = NULL;
	for (int i = 0; i < n;++i) {
		s=(DLinkNode*)malloc(sizeof(DLinkNode));
		s->data = a[i];
		s->next = L->next;
		while (L->next != NULL) {
			L->next->prior = s;
		}
		L->next = s;
		s->prior = L;
	}
}

  注意:s->next=L->next;                                             

建立双链表(尾插法):

void CreateListF(DLinkNode*& L, ElemType a[], int n) {
	DLinkNode* s,*r;
	L = (DLinkNode*)malloc(sizeof(DLinkNode));
	r = L;
	for (int i = 0; i < n; ++i) {
		s = (DLinkNode*)malloc(sizeof(DLinkNode));
		s->data = a[i];
		r->next = s;
		s->prior = r;
		r = s;
	}
	r->next = NULL;
}

注意:r->next=NULL;
 

你可能感兴趣的:(数据结构,数据结构,算法)