04_双向链表

本文深入探讨了双向链表的数据结构,详细解释了它的特点和优势,并通过C++代码展示了如何创建和操作双向链表,包括插入、删除节点等基本操作。
摘要由CSDN通过智能技术生成
#include <iostream>
using namespace std;

// 定义双向链表的节点类型
struct Node
{
   
	Node(int data = 0)
		: data_(data)
		, next_(nullptr)
		, pre_(nullptr)
	{
   }
	int data_;   // 数据域
	Node* next_; // 指向下一个节点
	Node* pre_;  // 指向前一个节点
};

// 双向链表
class DoubleLink
{
   
public:
	DoubleLink()
	{
   
		head_ = new Node();
	}
	~DoubleLink()
	{
   
		Node* p = head_;
		while (p != nullptr)
		{
   
			head_ = head_->next_;
			delete p;
			p = head_;
		
下面是一个简单的双向链表实现通讯录的 Java 代码: ```java public class Contact { private String name; private String phone; private Contact prev; private Contact next; public Contact(String name, String phone) { this.name = name; this.phone = phone; this.prev = null; this.next = null; } public void setPrev(Contact prev) { this.prev = prev; } public void setNext(Contact next) { this.next = next; } public Contact getPrev() { return prev; } public Contact getNext() { return next; } public String getName() { return name; } public String getPhone() { return phone; } } public class ContactList { private Contact head; private Contact tail; public ContactList() { head = null; tail = null; } public void addContact(String name, String phone) { Contact newContact = new Contact(name, phone); if (head == null) { head = newContact; tail = newContact; } else { tail.setNext(newContact); newContact.setPrev(tail); tail = newContact; } } public void removeContact(String name) { Contact current = head; while (current != null) { if (current.getName().equals(name)) { if (current == head) { head = current.getNext(); if (head != null) { head.setPrev(null); } } else if (current == tail) { tail = current.getPrev(); if (tail != null) { tail.setNext(null); } } else { current.getPrev().setNext(current.getNext()); current.getNext().setPrev(current.getPrev()); } break; } current = current.getNext(); } } public void printContacts() { Contact current = head; while (current != null) { System.out.println(current.getName() + " - " + current.getPhone()); current = current.getNext(); } } } ``` 这个实现中,`Contact` 类表示一个联系人,包含姓名、电话号码和前后指针。`ContactList` 类表示一个联系人列表,维护头尾指针,并提供添加、删除和打印联系人的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值