题目地址: https://leetcode-cn.com/problems/design-linked-list/
题目描述: 在链表类中实现这些功能:
get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。
addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。
参考代码:
class MyLinkedList {
struct ListNode {
int val;
ListNode *next;
ListNode():val(0),next(nullptr){};
ListNode(int x):val(x),next(nullptr){};
ListNode(int x,ListNode *next):val(x),next(nullptr){};
};
private: ListNode *head;
int size = 0;
public:
MyLinkedList() {
head = new ListNode(0);
size = 0;
}
int get(int index) {
if (index < 0 || index >= size) { // size - 1 是 最后1个
return - 1;
}
ListNode *temp = head;
while (index >= 0) {
temp = temp->next;
index --;
}
return temp->val;
}
void addAtHead(int val) {
ListNode *newData = new ListNode(val);
newData->next = head->next;
head->next = newData;
size = size + 1;
}
void addAtTail(int val) {
ListNode *pre = head;
ListNode *cur = head->next;
while (cur) {
pre = cur;
cur = cur->next;
}
ListNode *newData = new ListNode(val);
pre->next = newData;
newData->next = cur;
size ++;
}
void addAtIndex(int index, int val) {
if (index < 0 || index > size) {
return;
}
ListNode *pre = head;
while (index --) { // 找到前1个
pre = pre->next;
}
ListNode *newData = new ListNode(val);
newData->next = pre->next;
pre->next = newData;
size ++;
}
void deleteAtIndex(int index) {
if (index < 0 || index >= size) { // 0 - size -1
return;
}
ListNode *pre = head;
while (index --) { // 找到前1个
pre = pre->next;
}
ListNode *temp = pre->next;
pre->next =pre->next->next;
delete temp;
size --;
}
void printLinkedList() {
ListNode * cur = head;
while (cur->next != nullptr) {
cout << cur->next->val << " ";
cur = cur->next;
}
cout << endl;
}
};
网友评论