设计在无结点的单链表中删除第i个结点的算法

需要有创建无结点的单链表的过程,并且注释上解释
2024-12-22 12:52:52
推荐回答(1个)
回答1:

#include
#include

typedef struct Link
{
int num ;
struct Link *next;
}L;

void link( struct Link * head) //链表逆序
{
L *p, *q ,*temp, *temp2 ;
p = head ;
temp2 = q = head->next ;
while (q!=NULL)
{
temp = q->next ;
q -> next = p;
p = q ;
q = temp ;
}
temp2 ->next = NULL ;
head ->next = p ;
}

void output(struct Link *head)
{
L *p ;
p = head->next;
while (p != NULL)
{
printf("%d\n",p->num);
p = p->next;
}
}

void buildLink(struct Link * head)
{
L *p, *q ;
q = head;
int i;
for ( i = 1; i <= 5 ; i++)
{
p=(L *)malloc(sizeof(L));
p->num = i;
q->next=p;
q = p;
}
p->next = NULL;
}

int ListLength(L *head)
{
L*p;
int len;
for(p=head,len=0;p->next!=NULL;p=p->next,len++);
return(len);
}

//在链表中第i个数据元素之前插入数据元素e
int ListInsert(L *head,int i,int e)
{
L *p, *s=(L *)malloc(sizeof(L));
int j;
//检查i值的合理性
if(i<1||i>ListLength(head)+1) return 0;
s->num=e;
//寻找第i-1个结点
for(p=head,j=0;p&&jnext,j++);
s->next=p->next;
p->next=s;//将s结点插入
return 1;
}

//将链表中第i个数据元素删除
int ListDelete(L *head,int i)
{
L *p,*s;
int j;
//检查i值的合理性
if(i<1||i>ListLength(head)) return 0;
//寻找第i-1个结点
for(p=head,j=0;jnext,j++);
s=p->next;//用s指向将要删除的结点
p->next=s->next;//删除s指针所指向的结点
free(s);
return 1;
}

void main()
{
L *p, *q , *head ;//*temp, *temp2 ;
head=(L *)malloc(sizeof(L));
// q = head;

buildLink(head); //建立链表

output(head); //输出链表

ListInsert(head, 3 , 6);

printf("length=%d\n",ListLength(head));
output(head);
ListDelete(head, 4);
output(head);
printf("now length=%d\n",ListLength(head));

link(head); //链表逆序

printf("After action\n");

output(head);
}