建立单链表,并在单链表上实现插入、删除和查找操作 代码
时间: 2023-06-01 10:08:07 浏览: 97
单链表的创建,插入,删除,遍历代码
可以的,以下是示例代码:
// 定义链表结点
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// 定义链表类
class LinkedList{
private:
ListNode *head;
public:
LinkedList() : head(NULL) {}
// 插入结点,位置从1开始计数
void insert(int val, int pos){
ListNode *newNode = new ListNode(val);
if(pos == 1){
newNode->next = head;
head = newNode;
return;
}
ListNode *p = head;
for(int i = 1; i < pos-1; i++){
if(p == NULL) return;
p = p->next;
}
if(p == NULL) return;
newNode->next = p->next;
p->next = newNode;
}
// 删除结点,位置从1开始计数
void remove(int pos){
if(head == NULL) return;
if(pos == 1){
ListNode *tmp = head;
head = head->next;
delete tmp;
return;
}
ListNode *p = head;
for(int i = 1; i < pos-1; i++){
if(p == NULL) return;
p = p->next;
}
if(p == NULL || p->next == NULL) return;
ListNode *tmp = p->next;
p->next = p->next->next;
delete tmp;
}
// 查找结点,从头开始
int find(int val){
ListNode *p = head;
int pos = 1;
while(p != NULL){
if(p->val == val) return pos;
p = p->next;
pos++;
}
return -1;
}
};
// 测试
int main(){
LinkedList linkedList;
linkedList.insert(1, 1); // 1
linkedList.insert(2, 1); // 2 1
linkedList.insert(3, 2); // 2 3 1
linkedList.remove(2); // 2 1
cout << linkedList.find(2) << endl; // -1
cout << linkedList.find(1) << endl; // 2
return 0;
}
阅读全文