虽然不太清楚你想要啥,给你看看我的写法,希望对你有帮助:
struct CListNode{
int d;
CListNode* next;
};
struct CList{
int length;
CListNode* head;
};
CList* CListNew(int n) {
CList* l = (CList*)malloc(sizeof(CList));
l->length = n;
l->head = NULL;
if (n > 0) {
l->head = (CListNode*)malloc(sizeof(CListNode));
l->head->next = NULL;
l->head->d = -1;
}
CListNode* p = l->head;
for(int i=1; iCListNode* q = (CListNode*)malloc(sizeof(CListNode));
q->next = NULL;
q->d = -1;
p->next = q;
p = q;
}
return l;
}
void CListDelete(CList* l) {
CListNode* p = l->head;
while (p != NULL) {
CListNode* q = p->next;
free(p);
p = q;
}
free(l);
}
bool CListRemove(CList* l, int index) {
CListNode* p = l->head;
CListNode* prev = NULL;
for(int i = 0; i < index; i++) {
prev = p;
p = p->next;
}
if (p == NULL)
{ return false; }
if (prev == NULL)
{ l->head = p->next; }
else
{ prev->next = p->next; }
free(p);
l->length -= 1;
return true;
}
void CListInput(CList* l) {
CListNode* p = l->head;
while (p != NULL) {
scanf("%d", &p->d);
p = p->next;
}
}
void CListPrint(CList* l) {
CListNode* p = l->head;
printf("[");
if (p != NULL) {
while (true) {
printf("%d", p->d);
p = p->next;
if (p == NULL) {
break;
}
printf(",");
}
}
printf("]");
}
int main() {
CList* l = CListNew(3);
CListInput(l);
CListRemove(l,1);
CListPrint(l);
CListDelete(l);
return 0;
}
int main ()
{
int n,i;
LNode *head,*p;
//指针p没有用,这段可以注释掉
// p=(LNode*)malloc(sizeof(LNode));
// p->next=NULL;
// head=p;
LNode *create(int);
int DeleteLink(LNode *, int);
int Print(LNode *,int);
printf("How many nodes do you want in this linklist?\n");
scanf("%d",&n);
head = create(n); //原始代码返回的链表头指针没有复制给phead
printf("Which node do you want to delete?\n");
scanf("%d",&i);
DeleteLink(head,i);
Print(head,n-1);
return 0;
}
另外,给出的Print函数的定义有误,应该是前面忘记了返回类型int
代码就不能按照C++的格式贴出来吗?脑袋都看晕了