以下这段链表的搭建过程可以让人学习到很多的东西
#include <iostream>
#include "stdlib.h";
using namespace std;
class MyLinkedList {
public:
struct ListNode {
int val;
ListNode * next;
ListNode(int x) :val(x), next(NULL) {}
};
ListNode *head;
MyLinkedList() {
head = NULL;
}
int get(int index) {
if (index < 0 || head == NULL)return -1;
int i = 0;
ListNode *temp = head;
while (i < index&&temp->next!=NULL) {
temp = temp->next;
i++;
if (i == index)break;
}
if (i == index)return temp->val;
else return -1;
}
void addAtHead(int val) {
if (head == NULL) {
head = new ListNode(val);
}
else {
ListNode *temp = new ListNode(val);
temp->next = head;
head = temp;
}
}
void addAtTail(int val) {
ListNode *temp = head;
if (temp == NULL)temp = new ListNode(val);
else {
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = new ListNode(val);
}
}
void addAtIndex(int index, int val) {
if (index < 0)return;
if (head == NULL) {
if (index > 0) {
return;
}
else {
head = new ListNode(val);
return;
}
}
int i = 0;
ListNode * temp = head;
ListNode *last = NULL;
while (i < index&&temp->next != NULL) {
last = temp;
temp = temp->next;
i++;
if (i == index)break;
}
if (i == index) {
if (i == 0) {
temp = new ListNode(val);
temp->next = head;
head = temp;
}
else {
last->next = new ListNode(val);
last->next->next = temp;
}
}
else if (i == index - 1) {
temp->next = new ListNode(val);
}
}
void deleteAtIndex(int index) {
if (index < 0 || head == NULL)return;
int i = 0;
ListNode *temp = head;
ListNode *last = NULL;
while (i < index&&temp->next != NULL) {
last = temp;
temp = temp->next;
i++;
if (i == index)break;
}
if (i == index) {
if (i == 0) {
delete head;
head = NULL;
}
else {
last->next = temp->next;
delete temp;
}
}
}
void print() {
ListNode *p = head;
while (p!= NULL) {
cout << p->val << " ";
p = p->next;
}
cout << endl;
}
};