单链表的的创建,测长,打印,插入(附代码解析)

具体代码如下:所实现的是一个带头结点的链表

/*
单链表的插入分为三种方法,在头结点插入,在中间插入,在末尾插入
*/

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct node    //创建一个结点,用来存储信息
{
    int data;
    struct node*next;
 }node;       
 
 node*creat()   //单链表的建立
 {
    node*head,*p,*q;
    char ch;
    head=(node*)malloc(sizeof(node));
    q=head;
    ch='*';
    puts("单链表尾插法,?结束");   //用?来作为结束标志
    while(ch!='?')
    {
        int a; 
        scanf("%d",&a);
        p=(node*)malloc(sizeof(node));
        p->data=a;
        q->next=p;
        q=p;
        ch=getchar();
     }
     q->next=NULL;
     return(head);
 }
 
 void print(node*a)   //单链表的打印
 {
    puts("print ");
    a=a->next;
    while(a!=NULL)
    {
        printf("%d ",a->data);
        a=a->next;
     }
  }
  
 int length_node(node *head)  //单链表的测长
 {
	 int len=0;
	 node *p=head->next;
	 if(p!=NULL)
	 {
		 len++;
		 p=p->next;
	 }
	 return len;
 }
 
 node* insert_node(node*head,int data,int pos)    //单链表的插入,参数为头结点,插入的数字大小,插入的位置
 {
	 node* p;      //创建一个要插入的节点
	 int len=length_node(head);   //判断链表的长度
	 
	 p=(node *)malloc(sizeof(node));
	 if(p==NULL)
	 {
		 printf("申请空间失败");
		 exit(0);
	 }
	 p->data=data;
	 if(pos>len || pos<0)
	 {
		 printf("插入位置不合理\n");
		 exit(0);
	 }
	 if(pos==0)   //插在head后面,即在表头位置
	 {
		 p->next=head->next;
		 head->next=p;
		 return head;
	 }
	 else if(pos>0)
	 {
		 int i=1;
		 node *q=head->next;
		 for(i=1;i<pos;i++)   
		 {
			 q=q->next;
		 } 
		 if(q->next==NULL)  //插入链表末尾
		 {
		    q->next=p;
			p->next==NULL;
		 }
		 else if(q->next!=NULL)
		 {
		    p->next=q->next;   //插入链表中间位置
		    q->next=p;
		 }	 	 
	 }
 }

int main()
 {
    node*a;
    a=creat();
    print(a);
	insert_node(a,9,10);
    puts("\nhaved insert:"); 
    print(a);
	printf("\n");
    return 0;
 }

猜你喜欢

转载自blog.csdn.net/leikun153/article/details/80668692