首页 > 解决方案 > 这个链表实现有什么问题?

问题描述

设计你的链表实现。您可以选择使用单链表或双链表。单链表中的节点应该有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则需要多一个属性 prev 来指示链表中的前一个节点。假设链表中的所有节点都是 0-indexed。

class MyLinkedList {
public:
    /** Initialize your data structure here. */
     struct node{
           int val;
           struct node* next;
       }*first;
    MyLinkedList() {
      first=NULL;
    }
    
    /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
    int get(int index) {
       
        node* it=first;
        int i;
        for(i=0;i<index-1;i++)
        {
            
            it=it->next;
        
        }
        return it->val;
    }
    
    /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
    void addAtHead(int val) {
     node* p=new node;
     p->val=val;
     p->next=first;
     first=p;
    }
    
    /** Append a node of value val to the last element of the linked list. */
    void addAtTail(int val) {
       node* p=new node;
        p->val=val;
        p->next=NULL;
        node* it=first;
        while(it->next!=NULL)
        {
            it=it->next;
        }
        it->next=p;
    }
    
    /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
    void addAtIndex(int index, int val) {
        int i;
        node* it=first;
        node* prev=NULL;
        node* p=new node;
        p->val=val;
        for(i=0;i<index-1;i++)
        {
            prev=it;
            it=it->next;
        
        }
        prev->next=p;
        p->next=it;
        
    }
    
    /** Delete the index-th node in the linked list, if the index is valid. */
    void deleteAtIndex(int index) {
        int i;
        node* it=first;
        node* prev=NULL;
        for(i=0;i<index-1;i++)
        {
            prev=it;
            it=it->next;
        
        }
        prev->next=it->next;
        delete it;
    }
};

函数表达式具有以下含义,

get(index) :获取链表中第 index 个节点的值。如果索引无效,则返回 -1。

addAtHead(val) :在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。

addAtTail(val) :将值为 val 的节点附加到链表的最后一个元素。

addAtIndex(index, val) : 在链表中第 index 个节点之前添加一个值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于长度,则不会插入该节点。

deleteAtIndex(index) :如果索引有效,则删除链表中的第 index 个节点。

标签: c++algorithmdata-structureslinked-list

解决方案


以下是问题所在:

  • get()不检查索引是否无效。
  • addAtTail()不能很好地处理空列表。
  • addAtIndex()无法很好地处理第 0 个节点(头)之前的插入。
  • addAtIndex()不能很好地处理大于长度的索引。
  • deleteAtIndex()不能很好地处理第 0 个节点(头)的删除。
  • deleteAtIndex()不检查索引是否有效。

推荐阅读