c++在单链表中插入一个元素要求插入元素及位置用户自己输入
时间: 2024-06-12 10:06:24 浏览: 21
1. 首先需要定义一个节点结构体,包含要插入的元素和指向下一个节点的指针。
```
struct Node {
int data;
Node* next;
};
```
2. 然后定义一个单链表类,包含头节点和尾节点指针。
```
class LinkedList {
private:
Node* head;
Node* tail;
public:
LinkedList();
void insert(int element, int position);
};
```
3. 在单链表类的构造函数中,需要初始化头节点和尾节点指针。
```
LinkedList::LinkedList() {
head = nullptr;
tail = nullptr;
}
```
4. 在单链表类中定义插入函数。首先需要判断要插入的位置是否合法,如果位置超出范围,则提示错误信息。如果要插入的位置是头节点,则直接插入头节点。如果要插入的位置是尾节点,则直接插入尾节点。如果要插入的位置在中间,则需要遍历链表找到要插入的位置。
```
void LinkedList::insert(int element, int position) {
Node* newNode = new Node;
newNode->data = element;
newNode->next = nullptr;
if (position < 1) {
cout << "Invalid position." << endl;
return;
}
if (head == nullptr) {
head = newNode;
tail = newNode;
return;
}
if (position == 1) {
newNode->next = head;
head = newNode;
return;
}
int count = 1;
Node* current = head;
while (current != nullptr && count < position-1) {
current = current->next;
count++;
}
if (current == nullptr) {
cout << "Invalid position." << endl;
return;
}
newNode->next = current->next;
current->next = newNode;
if (newNode->next == nullptr) {
tail = newNode;
}
}
```
5. 在主函数中,可以创建一个单链表对象,然后调用插入函数进行测试。
```
int main() {
LinkedList list;
int element, position;
cout << "Enter element to be inserted: ";
cin >> element;
cout << "Enter position to insert: ";
cin >> position;
list.insert(element, position);
return 0;
}
```