题目链接
LeetCode707.设计链表
思路
按照题意模拟即可,我添加了头结点、尾结点、链表长度这几个长度进行辅助。有些细节需要注意,比如每次增删数据长度要变化,增删节点在头尾部需要更新head、tail,第一次添加元素需要对head、tail赋值等。
代码
class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int x){val=x;next=null;}
ListNode(int x,ListNode nxt){val=x;next=nxt;}
}
class MyLinkedList{
ListNode head,tail;
int lenth;
public MyLinkedList(){head=null;tail=null;lenth=0;}
public int get(int index){
if(index>=lenth||index<0)return -1;
ListNode p=head;
for(int i=0;i<index;i++)
p=p.next;
return p.val;
}
public void addAtHead(int val){
ListNode newNode=new ListNode(val);
if(head==null)
head=tail=newNode;
else{
newNode.next=head;
head=newNode;
}
lenth++;
}
public void addAtTail(int val){
ListNode newNode=new ListNode(val);
if(tail==null)
head=tail=newNode;
else{
tail.next=newNode;
tail=newNode;
}
lenth++;
}
public void addAtIndex(int index,int val){
if(index>lenth)return;
if(index<=0)
addAtHead(val);
else if(index==lenth)
addAtTail(val);
else{
ListNode p=head;
ListNode newNode=new ListNode(val);
for(int i=0;i<index-1;i++)
p=p.next;
newNode.next=p.next;
p.next=newNode;
lenth++;
}
}
public void deleteAtIndex(int index){
if(index<0||index>=lenth)
return;
else if(index==0)
head=head.next;
else {
ListNode p = head;
for (int i = 0; i < index-1;i++)
p=p.next;
p.next=p.next.next;
if(index==lenth-1)
tail=p;
}
lenth--;
}
}