zoukankan      html  css  js  c++  java
  • 单链表操作相关算法

    整理一些面试当中经常遇到的问题 帮助自己记忆.
    链表的类型: 单向链表,双向链表,循环链表

    C++ 链表的例子
    typedef struct IntElement {
      struct IntElement *next;
      int data;
    } IntElement;
    c# 实现 
    public class LinkNode {
       public LinkNode Next;
    public object Data;
    }
    操作链表常犯的错误:
    C#
    public void insertInFront( LinkNode list, Object data){
       LinkNode temp = new LinkNode();
       temp.Data = data;
       temp.next = list;   
    }
    错误原因是没有更新Header的引用, 解决的办法是使用引用参数 ref LinkNode 或者是返回新的头节点
    C++
    bool insertInFront(IntElement *head, int data){
         IntElement *newElement = new IntElement();
    if(!newElement) return false;
         newElem -> data = data;
    head = newElem;
    return true;
    }
    正确的方法应该是: 
    IntElement * insertInFront(IntElement *head, int data){
         IntElement *newElement = new IntElement();
    if(!newElement) return false;
         newElem -> data = data;
         newElem -> next = *head -> next;
    return newElem;
    }
     
    删除单链表的节点:
    bool deleteElement(IntElement** head, IntElement* deleteMe)
    {
        IntElement* element = *head;
        if(*head == deleteMe){
             *head = element ->next;
             delete deleteMe;
             return true;
        }
        while(element){
             if(element-> next == deleteMe){
                 element->next = deleteMe->next;
                 delete deleteMe;
                 return true;
             }
             element = element->next;
        }
        return false;
    }
     删除整个链表
     
    public void CleanList(IntElement** head){
       IntElement* element = *head;
       while(element){
           IntElement* next = element->next;
           delete element;
           element = next;
        }
        *head = NULL;
    }
     使用单链表实现一个栈.
     
     
  • 相关阅读:
    Mac国内源安装brew
    linux基础命令(二)
    运维查看命令
    初识数据库
    镜像/容器相关操作
    docker基本命令
    Docker简介及部署
    CF1599A Weights 构造
    CSP-S 2021 游记
    GeOP 1.0开发成!
  • 原文地址:https://www.cnblogs.com/stone/p/1872256.html
Copyright © 2011-2022 走看看