单向链表

2016-01-07  本文已影响0人  王小嘿

什么数据结构最优美,有人回答是数组。诚然,数组是很多数据结构的基础,就好比C语言在语言中的地位。但是当你做WEB开发的时候会用C语言来写吗?数组是程序设计语言中提供的非常有用的数据结构,但是,数组至少有两个局限性:
(1)编译期要知道大小;
(2)数组中的数据在计算机内存中是以相同距离间隔开的,这意味着在数组中插入一个数据,需要移动该数组中的其它数据。
链表就不存在这些问题,链表是节点的集合,节点中储存着数据并连接到其它节点。分享一个新加坡一所学校做的很可爱的学习数据结构的网站VisuAlgo
下面是保存整数单向链表的实现:

//*************************intSLList.h*******************
//        singly-linked list class to store intergers
#ifndef DOUBLY_LINKED_LIST
#define DOUBLY_LINKED_LIST

 class IntSLLNode{
 public: IntSLLNode(){ 
                       next = 0; 
               } 
               IntSLLNode(int el, IntSLLNode *ptr = 0){
                       info = el; next = ptr;
               } 
               int info;
               IntSLList *next; 
 }; 

class IntSLList{ 
public: IntSLList(){ 
                 head = tail = 0; 
              } 
              ~IntSLList();
               int isempty(){
                         return head == 0; 
              } 
              void addToHead(int); 
        //  void addToTail(int); 
              int deleteFromHead(); 
        //  int deleteFromTail();  
        //  void deleteNode(int); 
              bool isIntList(int) const; 
private:
             IntSLLNode *head, *tail; 
};
 #endif
//*********************intSLList.cpp********************
#include <iostream>
#include "intSLLint.h"

IntSLList::~IntSLList(){
         for (IntSLLNode *p; !isEmpty(); ){
               p = head -> next;
               delete head;
               head = p;
         }
}
void IntSLList::addToHead (int el){
         head = new IntSLLNode (int el);
         if (tail = 0)
               tail = head;
}
int IntSLList::deleteFromHead(){
        int el = head ->info;
        IntSLLNode *tmp = head;
        if (head == tail)
               head = tail = 0;
        else head = head ->next;
        delete tmp;
        return el;
}
bool IntSLList::isInList(int el) const{
        IntSLLNode *tmp;
        for (tmp = head; tmp != 0 && !(tmp ->info ==el); tmp = tmp ->next);
        return tmp != 0;
}

其中实现了在链表的前面添加一个节点,在链表的前面删除一个节点以及查找;在链表的末尾添加/删除以及删除保存某个整数的节点的函数没有写出,道理差不多。

上一篇 下一篇

猜你喜欢

热点阅读