ps:按照力扣的单链表设计题目设计的,题目在最后
#include<iostream>
using namespace std;
typedef struct SinglyListNode{
int val;
SinglyListNode *next = NULL;
};
static int size=0;
class MyLinkedList {
public:
int get(int index);//找下标为index的结点,下标为 0-index
void addAtHead(int val);//在头添加结点
void addAtTail(int val);//在尾添加结点
void addAtIndex(int index, int val);//在index前添加结点
void deleteAtIndex(int index);//删除第index结点
void coutLinkedList();//打印链表
private:
//head为地址
SinglyListNode* head=NULL;
};
void MyLinkedList::addAtHead(int val) {
//输入新结点cur
SinglyListNode *cur = new SinglyListNode();
cur->val=val;
cur->next=head;
//指定cur为新head
head=cur;
size++;
}
void MyLinkedList::addAtTail(int val){
if(size==0){
addAtHead(val);
return;
}
SinglyListNode *pLastNode = head;
SinglyListNode LastNode =*pLastNode;
for(int i=0;i<size-1;i++){
pLastNode=pLastNode->next;
}
SinglyListNode *newNode=new SinglyListNode();
newNode->val=val;
newNode->next=NULL;
pLastNode->next=newNode;
size++;
}
void MyLinkedList::addAtIndex(int index, int val){
if(index<=0){
addAtHead(val);
return;
}
if(index==size){
addAtTail(val);
return;
}
if(index>size) return ;
SinglyListNode *SerNode=head;//0 1 2 a 3 4 5 3
//SerNode为index结点的地址,在这个结点前插入一个新的结点
for(int i=1;i<index;i++){
SerNode=SerNode->next;
}
//创建新的结点
SinglyListNode *newNode = new SinglyListNode();
newNode->val=val;
newNode->next=SerNode->next;//新结点的指针指向原链表后一个结点
//SerNode的next指向新结点
SerNode->next=newNode;
size++;
}
void MyLinkedList::deleteAtIndex(int index){
if(index<0||index>=size) return;
SinglyListNode *PrevNode=head;
SinglyListNode *NextNode;
SinglyListNode *MidNode;
if(index==0){
size--;
head=head->next;
delete PrevNode;
return;
}
if(index==size-1){
for(int i=1;i<size;i++){
PrevNode=PrevNode->next;
}
NextNode=PrevNode->next;
PrevNode->next=NULL;
delete NextNode;
size--;
return;
}
for(int i=1;i<index;i++){
PrevNode=PrevNode->next;
}
MidNode=PrevNode->next;
NextNode=MidNode->next;
PrevNode->next=NextNode;
delete MidNode;
size--;
return;
}
int MyLinkedList::get(int index){
if(index>=size||index<0||size==0) return -1;
SinglyListNode *SerNode=head;
for(int i=0;i<index;i++){
SerNode=SerNode->next;
}
cout<<SerNode->val<<endl;
return SerNode->val;
}
void MyLinkedList::coutLinkedList(){
SinglyListNode *a =head;
for(int i=0;i<size;i++){
cout<<a->val<<" ";
if(a->next==NULL) break;
a=a->next;
}
cout<<endl;
}
int main()
{
MyLinkedList linkedList;
linkedList.addAtHead(3);
linkedList.addAtTail(8);
linkedList.addAtIndex(1,5);
linkedList.coutLinkedList();
linkedList.get(0);
linkedList.deleteAtIndex(2);
linkedList.coutLinkedList();
return 0;
}
运行结果:
力扣题目:
提交结果: