静态,动态链表

本文介绍了如何使用C++实现静态链表(基于数组)、双向链表以及动态链表,包括插入、删除节点的方法,如头插法、尾插法和删除特定值的节点。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <algorithm>
using namespace std;

/*
静态链表: 数组实现链表的逻辑  a[x] = y: x的后继是y
1、已知链表开头元素是head, 最后一个元素的后继标记为-1, 遍历整张链表
for(int i=head; i!=-1; i=a[i])     for(p = head; p; p=p->next)
cout<<i<<" ";                      cout<<p->data<<" ";
2、向结点x的后面插入结点y
a[y]=a[x], a[x]=y     y->next=x->next, x->next=y
3、删除x的后继
a[x]=a[a[x]]     x->next=x->next->next

双向链表
struct node {
int data;
node *next, *prev;
}
1、已知p结点的位置, 删除p的后继
p->next->next->prev=p; p->next=p->next->next;
或 p->next=p->next->next; p->next->prev=p;
2、已知p结点的位置, 在p后面插入一个结点q
q->next=p->next; q->prev=p;
p->next->prev=q; p->next=q;  或 p->next=q; q->next->prev=q;

循环单链表:  rear->next=head
*/

/*
动态链表
单链表为什么要有头结点?
需要找前驱的操作就统一了
*/
struct node {
    int data;
    node *next;
}*head, *rear;

void push_front(int x) {
    node *s = (node*) malloc(sizeof (node));
    s -> data = x;
    s -> next = head -> next;
    head -> next = s;
}

void print() {
    node *p = head -> next;
    cout << "head->";
    while(p) {
        cout << p->data << "->";
        p=p->next;
    }
    cout << "^";
}

void push_back(int x) {
    node *s = (node*) malloc(sizeof (node));
    s -> data = x;
    s -> next = NULL;
    rear -> next = s;
    rear = s;
}

void insert_back(int x, int y) {
    node *p = head -> next;
    while(p) {
        if(p -> data == x) {
            node *s = (node*) malloc(sizeof (node));
            s -> data = y;
            s -> next = p -> next;
            p -> next = s;
            return;
        }
    }
}

//双指针来实现删除
void erase(int x) {
    node *fast, *slow;
    fast = slow = head;
    while(fast) {
        slow = fast;
        fast = fast -> next;
        if(fast && fast -> data == x) {
            slow -> next = fast -> next;
            return;
        }
    }
}

//双指针实现前插操作
void insert_front(int x, int y) {
    node *fast, *slow;
    fast = slow = head;
    while(fast) {
        slow = fast;
        fast = fast -> next;
        if(fast && fast -> data == x) {
            node *s = (node*) malloc(sizeof (node));
            s -> data = y;
            s -> next = fast;
            slow -> next = s;
            return;
        }
    }
}

int main() {
    head = (node*) malloc(sizeof (node));
    head -> next = NULL;
    rear = head;

//头插法创建单链表
//push_front(1);push_front(2);push_front(3);push_front(4);push_front(5);
//尾插法创建单链表
    push_back(10);
    push_back(20);
    push_back(30);
    push_back(40);
    push_back(50);

//insert_back(30, 100);

//erase(40);

    insert_front(30, 100);

    print();
    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值