C语言链表学习

来源:互联网 发布:网络分线器怎样插网线 编辑:程序博客网 时间:2024/05/22 01:23

链表:

     创建链表,一般步骤是申明一个结构体,结构体里面再定义一个指向结构体自己的指针,通过这个指针将一块一块的内存区穿起来。

              如:                            struct node *next;

              一块块的内存呢,自然是:malloc(sizeof(node))

              几个核心的语句:    s=(node *)malloc(sizeof(node));

                                              p->next=s;

                                              p=s;

                                     穿到最后,结束时用 p->next=NULL;

      求链表长度,不用说,从头遍历到尾,定义个变量n计数即可。

      删除节点:这篇文章是单链表,删除的要义就是:

                                 删节的前一个     要删除的节点    删节的后一个

                                      pre               p                    after

                                删之前他们的关系是:

                                     pre->next=p;

                                     p->next=after;

      显然,删除要做的步骤就是:

                                     pre->next=after   或   pre-next=p->next

      释放这块内存    free(p);



#include "stdafx.h"
#include "malloc.h"
#include "stdio.h"


struct student//定义一个学生类的结构体
{
int data;
struct student *next;
};


struct student *creat()//创建链表,返回头指针
{
   struct student *p,*head,*s;
   head = (struct student*)malloc(sizeof(struct student));
   int x,cycle=1;


   p = head;
   while (cycle)
   {
  printf("输入结点数据\n");
  scanf("%d",&x);
  if (x)
  {
  s=(struct student*)malloc(sizeof(struct student));
  s->data = x;
  p->next = s;
  p = s;
  }
  else
  cycle = 0;
   }
   head = head->next;
   p->next = NULL;
   return head;



int length(struct student *head)//计算链表的长度
{
struct student *p;
int n = 0;
p=head;
while (p)
{
n++;
p=p->next;
}


return n;
}


void printInfo(struct student *head)//打印链表链
{
struct student *p;
p=head;
while (p)
{
printf("data:%d\n",p->data);
p=p->next;
}
}


struct student *del(struct student *head,int num) //删除链表中的元素
{
struct student *p1,*p2;
p1=head;
while (num!=p1->data &&p1->next!=NULL )
{
p2=p1;
p1=p1->next;
}
if (num==p1->data)
{
if (p1==head)
{
head=p1->next;
free(p1);
}
else
{
p2->next=p1->next;
}
}
else
printf("没有符合要求的数据\n");
return head;


}


void _tmain(int argc, _TCHAR* argv[])
{


struct student *head;
head=creat();
printf("链表的长度是%d\n",length(head));
printInfo(head);

del(head,2);//删除一个链表结点的数据
printf("链表的长度是%d\n",length(head));
printInfo(head);


}


原创粉丝点击