# 双链表删除某个位置的结点时出现的问题

guihailiuli
• 474

c语言写的双链表，删除某个位置的结点p，代码如下：

``````#include <stdio.h>
#include <stdlib.h>

typedef struct DNode{
int data;
struct DNode *prior, *next;  //前驱和后继指针

DLNode *p, *r;
DList = (DLNode *)malloc(sizeof(DLNode));   //申请头结点
DList->next = NULL;
r = DList;
r->next = NULL;     //r指向终端结点指针
int x;
printf("请输入双链表中元素的值,以负数作为结束输入：");
scanf("%d", &x);
while(x >= 0) {
p = (DLNode *)malloc(sizeof(DLNode));
p->data = x;
//尾插法
p->next = r->next;
r->next = p;
r = p;
scanf("%d", &x);
}
r->next = NULL;
return DList;
}

DLNode *p;
p = DList->next;
printf("打印双链表:");
for(p; p != NULL; p = p->next) {
printf("%6d", p->data);
}
printf("\n");
}

int n = 0;
DLNode *p;
p = DList->next;
for(p; p != NULL; p = p->next) {
n++;
}
return n;
}

DLNode *GetElemP(DLinkList DList, int i) {
int j;
DLNode *p;
p = DList;
for(j = 1; j <= i; j++) {
p = p->next;
}
return p;
}

//删除某个位置的结点p
int deleteDLIndex(DLinkList &DList, int delLocate) {
DLNode *p, *q;
if(delLocate < 1 || delLocate > DLinkLen(DList)) {
printf("删除位置不合适");
return -1;    //删除位置不合适
}
p = GetElemP(DList, delLocate);
if(!p) {
printf("p获取失败 ");
return -1;     //p获取失败
}
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
printf("该位置上的元素已经删除\n");
}

int main() {
printf("双链表建立完成\n");

int length;
printf("该双链表的长度: %d\n", length);

int delLocate;
printf("删除某个位置上的元素\n");
printf("请输入想要删除的位置: ");
scanf("%d", &delLocate);
deleteDLIndex(DList, delLocate);
}``````

2 个回答
✓ 已被采纳

``````DLinkList DLinkListCreate(DLinkList &DList) {
DLNode *p, *r;
DList = (DLNode *)malloc(sizeof(DLNode));   //申请头结点
DList->next = NULL;
DList->prior = NULL;
r = DList;
// r->next = NULL;     //r指向终端结点指针
int x;
printf("请输入双链表中元素的值,以负数作为结束输入：");
scanf("%d", &x);
while(x >= 0) {
p = (DLNode *)malloc(sizeof(DLNode));
p->data = x;
p->next = 0;
p->prior = r;
//尾插法
r->next = p;
r = p;

scanf("%d", &x);
}

return DList;
}``````

``int deleteDLIndex(DLinkList &DList, int delLocate)``

``int deleteDLIndex(DLinkList DList, int delLocate)``

``deleteDLIndex(DList, delLocate);``

``deleteDLIndex(&DList, delLocate);``

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进