zoukankan      html  css  js  c++  java
  • [google面试CTCI] 2-0.链表的创建

    创建链表、往链表中插入数据、删除数据等操作,以单链表为例。


    1.使用C语言创建一个链表:

    typedef struct nd{
      int data;
      struct nd* next; } node;
    //初始化得到一个链表头节点
    node* init(void){
       node* head=(node*)malloc(sizeof(node));
      if(head==NULL) return NULL;
      head->next=NULL;
      return head;
    }
    //在链表尾部插入数据
    void insert(node* head,int data){
       if(head==NULL) return;
      node* p=head;
      while(p->next!=NULL)
        p=p->next;
      node* new=(node*)malloc(sizeof(node));
       if(new==NULL) return;
      new->data=data;
      new->next=NULL;//新节点作为链表的尾节点
      p->next=new;//将新的节点链接到链表尾部
    }
    //从链表中删除一个节点,这里返回值为空,即不返回删除的节点
    void delete(node* head,int data){
      if(head==NULL) return ;
      node *p=head;
      if(head->data==data){//如何头节点为要删除的节点
        head=head->next;//更新链表的头节点为头节点的下一个节点
        free(p);
        return;
      }
      node *q=head->next;
      while(q!=NULL){
         if(q->data==data){//找到要删除的节点q
          node *del=q;
          p->next=q->next;
           free(del);
         }
        p=q;//不是要删除的节点,则更新p、q,继续往后找
        q=q->next;
       }
    }

    2.Java创建链表

    创建一个链表

    class Node {
      Node next = null;
       int data;
      public Node(int d) { data = d; }
      void appendToTail(int d) {//添加数据到链表尾部
        Node end = new Node(d);
        Node n = this;
        while (n.next != null) { n = n.next; }
        n.next = end;
      }
    }
    从单链表中删除一个节点
    Node deleteNode(Node head, int d) {
       Node n = head;
      if (n.data == d) { return head.next; /* moved head */ }
      while (n.next != null) {
        if (n.next.data == d) {
           n.next = n.next.next;
           return head; /* head didn’t change */
        } n = n.next;
       }
    }
    作者:Viidiot   微信公众号:linux-code

  • 相关阅读:
    springboot文件上传: 单个文件上传 和 多个文件上传
    Eclipse:很不错的插件-devStyle,将你的eclipse变成idea风格
    springboot项目搭建:结构和入门程序
    POJ 3169 Layout 差分约束系统
    POJ 3723 Conscription 最小生成树
    POJ 3255 Roadblocks 次短路
    UVA 11367 Full Tank? 最短路
    UVA 10269 Adventure of Super Mario 最短路
    UVA 10603 Fill 最短路
    POJ 2431 Expedition 优先队列
  • 原文地址:https://www.cnblogs.com/jjdiaries/p/3378743.html
Copyright © 2011-2022 走看看