应该怎么修改代码
这是题目:描述
给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。
(链表中的节点个数大于等于n)
样例
Example 1:
Input: list = 1->2->3->4->5->null, n = 2
Output: 1->2->3->5->null
Example 2:
Input:list = 5->4->3->2->1->null, n = 2
Output: 5->4->3->1->null
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node *next,*prior;
}LinkList;
LinkList*CreatList(int n)
{
LinkList*L;
LinkList *r,*p,*s;
r=L;
p=L;
DataType a;
int i=1;
scanf("%d",&a);
L = (LinkList*)malloc(sizeof(LinkList));//建立双链表
r->next=NULL;
while(a!=-1)
{
s=(LinkList*)malloc(sizeof (LinkList));
s->data=a;
s->next=r->next;
r->next=s;
s->prior=r;
r=r->next;
scanf("%d",&a);
}
int j;
int m;
while(p->next!=NULL)//遍历查看节点数量
{
int j=1;
p=p->next;
++j;
}
if(j<n)
return 0;
else
{
LinkList *t,*u,*v;
for( m=1;m<n;++m)//寻找需要删除的节点
{
t=r;
t=t->prior;
}
u=t->prior;
v=t->next;
v->prior=t->prior;
u->next=t->next;
free(t);
}
}
main()
{
printf("please input a number");
int n;
scanf("%d",n);
CreatList(n);
}
是哪里需要修改,希望大佬帮助。 @巴巴鲁 愷龍 发表于 2020-11-19 07:31
@巴巴鲁
好家伙,我还得写个打印函数
按你这思路做出来的是删除第几个元素,而不是倒数第几个
你自己再想想
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node *next, *prior;
}LinkList;
void Print(LinkList *head)
{
LinkList *p = head->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
}
LinkList*CreatList(int n)
{
LinkList*L;
LinkList *r, *p, *s;
DataType a;
int i = 1;
scanf("%d", &a);
L = (LinkList*)malloc(sizeof(LinkList));//建立双链表
// 头结点指向空,赋值语句放到初始化之后
L->next = NULL;
r = L;
p = L;
r->next = NULL;
while (a != -1)
{
s = (LinkList*)malloc(sizeof(LinkList));
s->data = a;
s->next = r->next;
r->next = s;
s->prior = r;
r = r->next;
scanf("%d", &a);
}
int j = 1;
int m;
while (p->next != NULL)//遍历查看节点数量
{
//int j = 1; // 外面已经定义了,循环里再定义?
p = p->next;
++j;
}
if (j<n)
return 0;
else
{
LinkList *t, *u, *v;
t = r;
for (m = 1; m<n; ++m)//寻找需要删除的节点
{
t = t->prior;
}
u = t->prior;
v = t->next;
v->prior = t->prior;
u->next = t->next;
free(t);
printf("删除成功!\n");
}
Print(L);
}
int main()
{
printf("please input a number");
int n;
scanf("%d", &n); // 取值符,到现在怎么还犯这种错误!
CreatList(n);
}
页:
[1]