c语言链表基本操作

1、链表定义

typedef struct listnode{
   int n;   //数据域
   struct listnode*next;//指针域
}listnode;

2、链表初始化

listnode *creatlist()
{
   listnode*head = (listnode*)malloc(sizeof(listnode));
   head->next=null;
   return head;
}

注:头结点只有指针域没有数据域
3、创建新节点

listnode *creatlistnode()
{
   printf(please input data:\n);
   scanf("d%",&data);
   listnode*node = (listnode*)malloc(sizeof(listnode));
   node->next=null;
   node->n=data;
   return node;
}

4、头插法

void insertlisthead(listnode*head)
{
   int i,n;
   printf(please input size:\n);
   scanf("d%",&n);
   for( i =0;i<n;i++)
   {
   //插入前首先创建新节点
   listnode*newnode = creatlistnode();
   newnode->next =head->next;
   head->next = newnode;
   }
}

5、尾插法

void  insertlisttail(listnode*head)
{
   int i,n;
   listnode*tail = (listnode*)malloc(sizeof(listnode));
   head = tail;
   printf(please input size:\n);
   scanf("d%",&n);
   for( i =0;i<n;i++)
   {
    listnode*newnode = creatlistnode();
    newnode->next = tail->next;
    tail->next = newnode;
    tail = newnode;
   }
}

6、打印输出链表

void printlist(listnode*head)
{
  listnode *p = head->next;
  while(p)
  {
  print("d%",p->n);
  p=p->next;
  }
  print ("\n")
}

7、指定位置删除节点

void delatenodelocate(listnode*head)
{
 int posdata;
 print("please input posdata:\n");
 scanf("d%",&posdata);
 listnode *p = head;
 listnode*posnode=head->next;
 while(posnode->n!=posdata)
 {
    p= p->next;
    posnode = posnode->next;
    if(posnode==NULL)
    {
       print("fail to delete");
       return;
    }
 }
 p->next= posnode->next;//找到要删除的节点 对其进行删除;
 free (posnode);
 
}

8、指定位置插入节点

void insertnodelocate(listnode*head)
{
 int pos;
 print("please input pos:\n");
 scanf("d%",&pos);
 listnode *p = head;
 listnode*posnode=head->next;

for(int i =0;i<pos-1;i++)
{
 p=p->next;
 posnode=posnode->next;
}
 listnode*newnode = creatlistnode();  
  p->next = newnode;
  newnode->next =posnode;
}

9、判断是否为空

bool EmptyList(listnode* Head)
{
	if(Head->next)
	{
		printf("not Empty!\n");
		return 0;
	}
	else
	{
		printf("Empty!\n");
		return 1;
	}
}

10、清空链表

void cleanlist(listnode*head)
{
  listnode*p,*q;
  p=head->next;
  while(p)
  {
   q=p->next;
   free(p);
   p=q;
  }
  head->next=null;
 
}

11、求链表长度

int Length(ListNode* Head)
{
	ListNode* p=Head;
	int count=0;
	while(p->next!=NULL)
	{
		count++;
		p=p->next;
	}
	printf("Length:%d\n",count);
	return count;
}
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值