带表头结点单链表的初始化、查找、插入、删除、输出、撤销

本文介绍了带表头结点的单链表数据结构,详细阐述了如何进行初始化、查找特定元素、插入新节点、删除指定节点以及实现撤销操作的步骤,帮助理解链表的基本操作。
摘要由CSDN通过智能技术生成
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>

#define ERROR 0
#define OK 1
#define Overflow 2
#define Underflow 3
#define NotPresent 4
#define Duplicate 5

typedef int ElemType;
typedef int Status;
//带表头结点单链表的定义
typedef struct node
{
   
    ElemType element;
    struct node *link;
}node;

typedef struct
{
   
    struct node *head;
    int n;
}headerList;

//带表头结点单链表的初始化
Status Init(headerList *h)
{
   
    h->head = (node*)malloc(sizeof(node));
    if(!h->head)
        return ERROR;
    h->head->link = NULL;
    h->n = 0;
    return OK;
}

//带表头结点单链表的插入
Status Insert(headerList *L,int i,ElemType x) //在i后面插入x
{
   
    if(i<-1||i>L->n-1)
        return ERROR;
    node *p = L->head;
    int j;
    for(j=0;j<=i;j++)
        p = p->link;
    node *q 
  • 11
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是带表头结点单链表的逆置操作的代码实现: ```c++ #include <iostream> using namespace std; // 定义单链表结点结构体 struct Node { int data; Node* next; }; // 定义单链表类 class LinkedList { private: Node* head; // 表头指针 public: // 构造函数 LinkedList() { head = new Node; head->next = NULL; } // 插入结点 void insertNode(int data) { Node* newNode = new Node; newNode->data = data; newNode->next = head->next; head->next = newNode; } // 查找结点 Node* findNode(int data) { Node* p = head->next; while (p != NULL && p->data != data) { p = p->next; } return p; } // 删除结点 void deleteNode(int data) { Node* p = head->next; Node* pre = head; while (p != NULL && p->data != data) { pre = p; p = p->next; } if (p != NULL) { pre->next = p->next; delete p; } } // 输出链表 void printList() { Node* p = head->next; while (p != NULL) { cout << p->data << " "; p = p->next; } cout << endl; } // 逆置链表 void reverseList() { Node* p = head->next; Node* pre = NULL; Node* next = NULL; while (p != NULL) { next = p->next; p->next = pre; pre = p; p = next; } head->next = pre; } }; int main() { LinkedList list; list.insertNode(1); list.insertNode(2); list.insertNode(3); list.insertNode(4); list.insertNode(5); cout << "原链表:"; list.printList(); list.reverseList(); cout << "逆置后的链表:"; list.printList(); return 0; } ``` 说明: - 在构造函数中,创建了一个带表头结点的空链表,表头指针为 head,并将头结点的 next 指针初始化为 NULL。 - insertNode() 方法实现了向链表中插入新结点的功能。新结点的 next 指针指向原先的第一个结点,头结点的 next 指针指向新结点。 - findNode() 方法实现了查找指定数据的结点的功能,返回该结点的指针。如果未找到,则返回 NULL。 - deleteNode() 方法实现了删除指定数据的结点的功能。先利用 findNode() 方法找到该结点,然后将该结点从链表中删除,并释放该结点所占用的内存。 - printList() 方法实现了输出链表的功能。 - reverseList() 方法实现了逆置链表的功能。利用三个指针 p、pre 和 next,依次将每个结点的 next 指针指向前一个结点。最后将头结点的 next 指针指向原先的最后一个结点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值