关于内存堆栈和链表

今日看了数据结构的第二章,讲到程序语言中链表的运用。还有斯坦福公开课关于内存的介绍,这里总结一下学习成果。

首先,链表作为一种数据结构,必定存储在内存当中。

其次,链表作为一种动态数组的存储方法,优点在于方便插入和删除数据,但是在搜索方面,比较繁琐。每次搜索必须从头开始遍历。

下面由代码来解释 如何创建链表 插入链表 删除链表 查找链表

首先是创建结构体。

struct student{
    int grade;
    char name[10];
    struct student *next;
};

  *next 是用于指向下一个头节点来对下一个节点进行操作的中间量

 

创建链表

struct* student create(){
    struct student *pt,*pn,*head;
    int n;
    scanf("%d",&n);
    pn = (struct student*)malloc(sizeof(struct student));
    scanf("%s %d",pn->name,&pn->grade);
    head = pt = pn;
    for(int i=1;i<n;i++)
{
     pn = (struct student*)malloc(sizeof(struct student));
     scanf("%s %d",pn->name,&pn->grade);
     pt->next = pn;
     pt = pn;
}
    pt->next = null;
    return head;

在表头插入节点

pn = (struct student*)malloc(sizeof(struct student));
    scanf("%s %d",pn->name,&pn->grade);
    pn->next = head;
    head = pn;
    return head;

删除和查找殊途同归,先查找关键字,然后删除节点。

   
  struct student *p,*pold; char name[10]; scanf("%s",name); p = head; while(head!=null&&head->name == name) //如果查找的人在头节点 { head = head->next; free(p); p=head; } if(head == null) return head;
p
=head->next; //遍历链表的操作 pold = head; while(p!=null){ if(p->name == name) { pold->next = p->next; free(p); p = pold->next; } else { pold = p; p = p->next; } return head;

如果单纯查找,不删除,则不用pold

while(p!=null)
{
    if(p->name == name)
      return p;
    p=p->next
}
return null;

 

这是最简单的单向链表的简单操作,还要继续学习

posted @ 2016-04-29 14:11  Forri  阅读(1042)  评论(0编辑  收藏  举报