算法--循环单链表删除数值相同的元素

来源:互联网 发布:java 多口短信猫 编辑:程序博客网 时间:2024/06/05 20:33

DeleteNode(LinkList L)

{

   Node *p,q;

   q=L;                                       //q指向头指针;

While(q->next!=L)

{

    P=q->next;                           //p指向第一个节点;

    q=q->next;

    while(p->next!=L)                //这个while循环实现各个节点与其余节点的比较

     {

       if (p!=p->next)

          p=p->next;

       else

          p->next=p->next->next;

          delete(p->next);

       }

}

 

}

//可运行的代码

 

#include <stdio.h>
#include <malloc.h>
typedef struct LinkList
{
int elem;
struct LinkList *next;
}LList;

void CreatList( LList *L)
{
int ch;
  LList *s;
printf("please enter the date:");
scanf("%d",&ch);

while(ch!=0)/*当输入为0时结束输入 */
{
  s=malloc(sizeof( LList));
  s -> elem = ch;
  s ->next =L ->next;
  L -> next = s; 
  printf("please enter the date:");
  scanf("%d",&ch);
}
}

void reverse( LList *L)
{
LList *p,*r,*q;
  p=L;
  while(p)
  {
   q=p->next;
   r=p;
   while(q)
   {
    if(q->elem==p->elem)
    {
     r->next=q->next;
     free(q);
     q=r->next;
    }
    else
    {
     q=q->next;
     r=r->next;
    }
   }
   p=p->next;
  }
}

void display( LList *L)
{
LList *p;
int i=1;
printf("链表为:");
p=L->next;
while(p)
{
  printf("%d ",p->elem);
  i++;
  p=p->next;
}
}

void main()
{
  LList *L;
L=malloc(sizeof(LList));
L->next=NULL;
CreatList(L);
display(L);
reverse(L);
display(L);   
}

原创粉丝点击