单链表增删基础操作(Cpp, Java实现)
Cpp实现:
#include <cstdio>
using namespace std;
struct Node
{
int value;
Node* next;
Node() {}
Node(int v) : value(v), next(nullptr) {}
};
Node* head = nullptr;
void add(Node* node)
{
node->next = head;
head = node;
}
bool remove(int x)
{
if (!head) return false;
Node* p = head, * prev = p;
if (!x)
{
head = p->next;
delete p;
p = nullptr;
return true;
}
for (int i = 0; i < x && p; ++i)
{
prev = p;
p = p->next;
}
if (p)
{
prev->next = p->next;
delete p;
p = nullptr;
return true;
}
return false;
}
void print()
{
Node* p = head;
while (p)
{
printf("%d ", p->value);
p = p->next;
}
}
int main()
{
Node* node = new Node(1);
add(node);
add(new Node(2));
add(new Node(3));
print();
printf("\n");
remove(0);
print();
return 0;
}
Java实现:
import java.io.*;
public class Main
{
static class Node
{
int value;
Node next;
public Node() {}
public Node(int value)
{
this.value = value;
}
}
static Node head = null;
static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
static void add(Node node)
{
node.next = head;
head = node;
}
static boolean remove(int x)
{
if (head == null) return false;
Node p = head, prev = p;
if (x == 0)
{
head = p.next;
p = null;
return true;
}
for (int i = 0; i < x && p != null; ++i)
{
prev = p;
p = p.next;
}
if (p != null)
{
prev.next = p.next;
p = null;
return true;
}
return false;
}
static void print()
{
Node p = head;
while (p != null)
{
pw.printf("%d ", p.value);
p = p.next;
}
}
public static void main(String[] args) throws IOException
{
Node node = new Node(1);
add(node);
add(new Node(2));
add(new Node(3));
print();
pw.printf("\n");
remove(0);
print();
pw.close();
}
}