带头结点的单链表head中的结点是按整数值递增排序的

 

#include<stdio.h>
#include<stdlib.h>
# include<iostream>
using namespace std;
typedef struct node
{
	int data;
	struct node *next;
}Linklist;

Linklist *create() //创建带头
{
	Linklist *head;
	head=(Linklist *)malloc(sizeof(Linklist));
	head->next=NULL;
	return head;	
}

Linklist *tail_insert(Linklist *head, int value) //尾插法
{	Linklist *p,*t;
	t=head;
	p=(Linklist *)malloc(sizeof(Linklist));
	p->data=value;
	while(t->next!=NULL) //当链表不为空时t向后移动
	t=t->next; 
	t->next=p;
	p->next=NULL;
	return head;
}


Linklist *insert(Linklist *head,int value)//插入结点
{
    Linklist *p,*s; 
    p=head;
	while(p->next!=NULL) //
	{  
	
		if(p->next->data>value)    
		{	
	     s =(Linklist *)malloc(sizeof(Linklist)); /*生成新的结点*/
         s->data = value;
         s->next = p->next;
		 p->next=s;
         return head;
		}
		else	
	    	p=p->next;
	}
  
  return head;
}

Linklist  *del(Linklist *head,int value) //删除结点
{
	Linklist *p,*t;
	p=head;
	while(p->next!=NULL)
	{
		if(p->next->data==value)
		{ 
	 	    t=p->next;
			p->next=t->next;
			free(t);
			t=NULL;
		}
		else
			p=p->next;		
	}
	return head;
}

Linklist  *del_before(Linklist *head,int value) //删除前驱结点
{
	Linklist *p,*t;
	p=head;
	while(p->next!=NULL)
	{ 

         
		if(p->next->data==value)
		{ 
			t->next=p->next;
			
			return head;
		}
		else
			t=p;
			p=p->next;		
	}
	return head;
}


Linklist *display(Linklist *head) //打印链表数据
{
	Linklist *p;
	p=head->next;
	if(p==NULL)
	{
	printf("linklist is empty...\n");
	return head;
	}
	while(p!=NULL)
	{
	  printf("%3d",p->data);
	  p=p->next;	
	}
	printf("\n");	
	return head;
}





Linklist *sort(Linklist *head) //链表元素排序
{
	int i,j,t;
    int n=0;
    Linklist *p,*q;
    p=head->next;
    while(p!=NULL) 
    {
      n++;
      p=p->next;
     }
       for(i=0;i<n-1;i++) //冒泡排序
      {
         p=head->next;
         q=p->next;
            for(j=0;j<n-i-1;j++)
          { 
              if(p->data > q->data)
             {
               t=p->data;
               p->data=q->data;
               q->data=t;
              } 
              p=p->next;
              q=q->next;   
          }
       }
	return head;
}

int main()

{

	Linklist *head;
	int i, j,num;
	head=create();
	printf("tail_insert:\n");
//	for(i=2;i<20;i=i+4)
    int a[5] = {1, 2, 4, 3, 6};
	for(j=0;j<5;j++)
	{
	i=a[j];
	tail_insert(head,i);
	}

	display(head);
    
	printf("pop sort:\n");
	sort(head);
	display(head);

	printf("insert:\n");
	insert(head,5);
    display(head);

   printf("delet:\n");
   del(head,2);
   display(head);


   printf("delet_before:\n");
   del_before(head,5);
   display(head);
   
   return 0;

}

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页