数据结构语言建模源代码
时间: 2023-06-28 20:14:21 浏览: 79
以下是使用C++语言实现链表的示例代码:
```cpp
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class MyLinkedList {
public:
/** Initialize your data structure here. */
MyLinkedList() {
size = 0;
head = new ListNode(0);
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
if (index < 0 || index >= size) {
return -1;
}
ListNode* curr = head;
for (int i = 0; i < index + 1; i++) {
curr = curr->next;
}
return curr->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. */
void addAtHead(int val) {
addAtIndex(0, val);
}
/** Append a node of value val to the last element of the linked list. */
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. */
void addAtIndex(int index, int val) {
if (index > size) {
return;
}
if (index < 0) {
index = 0;
}
size++;
ListNode* prev = head;
for (int i = 0; i < index; i++) {
prev = prev->next;
}
ListNode* node = new ListNode(val);
node->next = prev->next;
prev->next = node;
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
size--;
ListNode* prev = head;
for (int i = 0; i < index; i++) {
prev = prev->next;
}
ListNode* curr = prev->next;
prev->next = curr->next;
delete curr;
}
private:
int size;
ListNode* head;
};
int main() {
MyLinkedList linkedList;
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1, 2); // linked list becomes 1->2->3
cout << linkedList.get(1) << endl; // returns 2
linkedList.deleteAtIndex(1); // now the linked list is 1->3
cout << linkedList.get(1) << endl; // returns 3
return 0;
}
```
以上是一个简单的链表实现,其中包括了插入、删除、查找等基本操作。在实现数据结构时,需要考虑到其应用场景和需要解决的问题,并根据需求进行相应的设计和实现。
阅读全文