双链表的代码实现:
主要是双链表的常用操作,末尾有目录,可以收藏
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
typedef struct DNode {
int data;
struct DNode* prior;
struct DNode* next;
}DNode, *DlinkList;
void initList(DlinkList &d) {
d = (DlinkList)malloc(sizeof(DNode));
d->next = NULL;
d->prior = NULL;
}
void HeadInsert(DlinkList &d, int x) {
DlinkList s;
if (d->next == NULL) {
s = (DlinkList)malloc(sizeof(DNode));
s->next = NULL;
s->prior = d;
d->next = s;
s->data = x;
}
else
{
s = (DlinkList)malloc(sizeof(DNode));
s->next = d->next;
d->next->prior = s;
s->prior = d;
d->next = s;
s->data = x;
}
}
int getLength(DlinkList d) {
int len = 0;
DlinkList s = d->next;
while (s != NULL){
len++;
s = s->next;
}
return len;
}
bool empty(DlinkList d) {
if (d->next == NULL) {
return true;
}
else
{
return false;
}
}
DlinkList getNode(DlinkList d, int index) {
if (!empty(d)) {
int len = getLength(d);
if (index < 1 || index > len) {
printf("查找越界\n");
return NULL;
}
else
{
int j = 1;
DlinkList s = d->next;
while (j < index) {
s = s->next;
j++;
}
return s;
}
}
else
{
printf("链表为空\n");
return NULL;
}
}
void tailList(DlinkList &d, int x) {
DlinkList s;
if (d->next == NULL) {
s = (DlinkList)malloc(sizeof(DNode));
s->next = NULL;
s->prior = d;
d->next = s;
s->data = x;
}
else
{
int len = getLength(d);
DlinkList t = getNode(d,len);
s = (DlinkList)malloc(sizeof(DNode));
s->next = NULL;
s->prior = t;
t->next = s;
s->data = x;
}
}
void showList(DlinkList d) {
DlinkList s = d->next;
while (s != NULL){
printf("%d\n", s->data);
s = s->next;
}
}
//按位删除
void deleteNodeByIndex(DlinkList &d, int index) {
int len = getLength(d);
if (empty(d)) {
printf("链表为空\n");
return;
}
if (index < 0 || index > len) {
printf("参数越界\n");
return;
}
if (index == len) {
DlinkList p = getNode(d, index - 1);
DlinkList q = getNode(d, index);
p->next = NULL;
q->prior = NULL;
free(q);
}
else if(index == 1)
{
DlinkList q = getNode(d, index);
d->next = q->next;
q->next->prior = d;
free(q);
}
else
{
DlinkList p = getNode(d, index - 1);
DlinkList q = getNode(d, index);
p->next = q->next;
q->next->prior = p;
free(q);
}
}
int main() {
DlinkList d;
initList(d);
//HeadInsert(d, 1);
//HeadInsert(d, 2);
//HeadInsert(d, 3);
//HeadInsert(d, 4);
tailList(d, 1);
tailList(d, 2);
tailList(d, 3);
tailList(d, 4);
showList(d);
deleteNodeByIndex(d, 1);
deleteNodeByIndex(d, 3);
showList(d);
}
查看考研数据结构目录:
https://www.acwing.com/file_system/file/content/whole/index/content/5394132/