单链表的多语言表达:C++、Java、Python、Go、Rust
以下是单链表的创建、插入、打印和删除操作的实现代码,在C++、Java、Python、Go和Rust中:
C++:
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
// 插入节点
void insert(ListNode*& head, int data) {
ListNode* newNode = new ListNode(data);
newNode->next = head;
head = newNode;
}
// 打印链表
void printList(ListNode* head) {
while (head != nullptr) {
std::cout << head->val << " ";
head = head->next;
}
std::cout << std::endl;
}
// 删除节点
void deleteNode(ListNode*& head, int data) {
if (head->val == data) {
ListNode* temp = head;
head = head->next;
delete temp;
return;
}
ListNode* current = head;
while (current->next != nullptr && current->next->val != data) {
current = current->next;
}
if (current->next != nullptr) {
ListNode* temp = current->next;
current->next = current->next->next;
delete temp;
}
}
int main() {
ListNode* head = nullptr;
insert(head, 4);
insert(head, 3);
insert(head, 2);
insert(head, 1);
printList(head); // 输出: 1 2 3 4
deleteNode(head, 3);
printList(head); // 输出: 1 2 4
return 0;
}
Java:
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Main {
// 插入节点
void insert(ListNode head, int data) {
ListNode newNode = new ListNode(data);
newNode.next = head;
head = newNode;
}
// 打印链表
void printList(ListNode head) {
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println();
}
// 删除节点
void deleteNode(ListNode head, int data) {
if (head.val == data) {
ListNode newHead = head.next;
head = null;
head = newHead;
return;
}
ListNode current = head;
while (current.next != null && current.next.val != data) {
current = current.next;
}
if (current.next != null) {
ListNode temp = current.next;
current.next = current.next.next;
temp = null;
}
}
public static void main(String[] args) {
ListNode head = null;
Main obj = new Main();
obj.insert(head, 4);
obj.insert(head, 3)
评论已关闭