【发布时间】:2020-08-24 14:14:57
【问题描述】:
设计您的链表实现。您可以选择使用单链表或双链表。单链表中的节点应该有两个属性: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 个节点。
【问题讨论】:
-
这个 Linked List 实现有什么问题? -- 它有什么问题吗?如果有问题,您应该在问题中说明问题所在。
-
肯定有一点是错的:它缺少一个析构函数。
-
请使用tour 并阅读How to Ask。此外,请考虑提取 minimal reproducible example 以使您的问题更具体。
-
是什么让你觉得有些不对劲?
-
在
get()、addAtIndex()和deleteAtIndex()这三种方法中,for(i=0;i<index-1;i++)这一行应该改为for(i=0;i<index;i++)。
标签: c++ algorithm data-structures linked-list