假设在长度大于1的单循环链表中,既无头结点也无头指针。s为指向某个结点的指针,试编写算法删除结点*s的直接前驱结点。

cl7106786 2011-10-13 07:48:40
#include<iostream.h>
#include<stdlib.h>
#include<stdio.h>
typedef int datatype;
typedef struct node
{
datatype data;
struct node *next;
} *linklist; //linklist结构体类型描述
/*void CreateList(linklist &L,int n)
{
L=(linklist)malloc(sizeof(node));
L->next=L;
L->data=0;

for(int i=0; i<n;i++)
{
node *p;
p=(linklist)malloc(sizeof(node));
cin>>p->data;

if(i==0)
{
L->next=p;
p->next=L;
}
else
{
p->next=L->next;
L->next=p;
}
}
}*/
void CreateList(linklist &L,int n)
{
int temp,x;
linklist q,p;
q = p;
scanf("%d",&temp);

p -> data = temp;
p->next = NULL;

for(int i=0; i<n-1;i++)
{
//cin>>x;
q=(linklist)malloc(sizeof(node)); //生成新的结点
//q -> data = x;
cin>>q->data;
q -> next = p;
p = q;
}


}

void DeleteBefore(linklist &L,node *s,int m)
{
struct node *p,*q;
p=s;
while(p->next->next!=s)
p=p->next;
q=p->next;
p->next=s;
if(q == L) // 如果删除头结点
L = s;
delete q;
// p=(linklist)malloc(sizeof(node));
//node *s;
/*for(int i=0;i<m-2;i++)
{
s=s->next;
}
// node *p;
p=s->next;
s->next=s->next->next;
free(p);
}*/



/*s=(linklist)malloc(sizeof(node));
p=L;
while(p->next->next!=s)
p=p->next;
free(p->next);
p->next=s;*/

}
void print(linklist L,int n)
{
//L=(linklist)malloc(sizeof(node));
//L->next=NULL;
struct node *p;
p=L->next;

for(int i=0;i<n;i++){

//p=(linklist)malloc(sizeof(node));

cout<<p->data<<endl;
p=p->next;
}
}
void main()
{
linklist A;
struct node *s;
/*cout<<"输入5个数"<<endl;
CreateList(A,5);
s=(linklist)malloc(sizeof(node));
s=A->next->next;
DeleteBefore(A,s);
print(A,4);
}*/
int n;
cout<<"输入链表的长度n"<<endl;
cin>>n;
cout<<"输入n个数"<<endl;
CreateList(A,n);
cout<<"输入要删除第几个的前结点"<<endl;
int x;
cin>>x;
s=A->next;
for(int i=0;i<x;i++)
{
s=s->next;
}
DeleteBefore(A,s,n);
cout<<"输出链表元素..."<<endl;
print(A,n-1);
}
刚开始还可以创建链表,现在改成没有头结点的链表之后,连创建也不行啦,各位同学请帮忙看一下吧
...全文
2328 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
miliggate 2012-03-10
  • 打赏
  • 举报
回复
把需要删除的节点与下一个节点的数据对换不久可以了吗
fuf123456789 2011-10-13
  • 打赏
  • 举报
回复
有几个字打错了。。。。分就别给了。。。。。
fuf123456789 2011-10-13
  • 打赏
  • 举报
回复
你可以读一遍链表 对了以后置移个标志 并把它放到一个数组中,就可以删除了。不过链表不能太长
AndyZhang 2011-10-13
  • 打赏
  • 举报
回复
太乱了,写个简单的尝试一下吧

69,370

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧