题面如下:(附有做题时的疑问和困惑)
设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。
在链表类中实现这些功能:
get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。
addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/design-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
下面为做题过程中遇到的问题:
问题1:为什么要写构造函数?
因为需要初始化,如果不写构造函数,那么你在实例化对象的时候就无法将值传入结构中。所以,以后写类,要记得写构造函数。
困惑1:为什么要定义 int size?定义一个为0的size,为什么可以表示所有链表的长度
题的意思并不是要给你传入一个链表,来对他进行操作。而是实例化一个空的链表,通过add和delete来操作链表,在操作过程中size值会发生变化。为什么要定义size值,是通过观察你所要实现的方法参数,如AddAtHead(int index,int val)便利时需要一个尾巴(size),来更加方便的判断何时停止遍历。
再把这两个问题弄清楚后,这道题就不会很难想了。
public class Node{
public Node Next{get;set;}
public int Val{get;set;}
public Node(int x){
Val=x;
}
}
public class MyLinkedList {
private int size;
private Node head;
/** Initialize your data structure here. */
public MyLinkedList() {
size=0;
head=new Node(0);
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
public int Get(int index) {
if(index<0 || index >= size){
return -1;
}
var current=head;
for(var i=0;i<index+1;i++){
current=current.Next;
}
return current.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. */
public void AddAtHead(int val) {
AddAtIndex(0,val);
}
/** Append a node of value val to the last element of the linked list. */
public void AddAtTail(int val) {
AddAtIndex(size,val);
}
/** 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. */
public void AddAtIndex(int index, int val) {
if(index > size){
return;
}
if(index < 0){
index=0;
}
size++;
var toAdd=new Node(val);
var pred=head;
for(var i=0;i<index;i++){
pred=pred.Next;
}
toAdd.Next=pred.Next;
pred.Next=toAdd;
}
/** Delete the index-th node in the linked list, if the index is valid. */
public void DeleteAtIndex(int index) {
if(index < 0 || index>=size) return;
size--;
var pred=head;
for(var i=0;i<index;i++){
pred=pred.Next;
}
pred.Next=pred.Next.Next;
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.Get(index);
* obj.AddAtHead(val);
* obj.AddAtTail(val);
* obj.AddAtIndex(index,val);
* obj.DeleteAtIndex(index);
*/