C++数据结构 单链表创建及操作实现

 

#include<iostream>
using namespace std;
struct Node
{
    int data;
    Node* next;
};
void Print(Node* head)
{
    Node* p;
    p = head->next;
    while (p)
    {
        cout << p->data << " ";
        p = p->next;
    }
    cout << endl;
}
void Set(Node* &head)
{
    Node* q, * p; int m, n;
    head = (Node*)new Node;
    head->next = NULL;
    q = head;
    cout << "正在创建单链表__请输入节点个数:";
    cin >> m;
    for (int i = 0; i < m; i++)
    {
        cout << "请输入节点数据:" << endl;
        cin >> n;
        p = (Node*)new Node;
        p->data = n;
        q->next = p; q = p;
    }
    q->next = NULL;
}
void Search(Node*&P,int n,int& pan)
{
    Node * q;
    int j = 0;
    while (P && j < n - 1)
    {
        P = P->next;
        j++;
    }
    if (!P || j > n - 1)
    {
        cout << "该位置不存在!" << endl;
        return;
    }
    pan = 1;
}
void Insert(Node* L) 
{
    int n,e,pan = 0;
    Node*P=L,* E;
    cout << "请输入要插入的位置" <<endl;
    cin >> n;
    Search(P,n,pan);
    if (pan == 0)
        return;
    cout << "请输入要插入的数据" <<endl;
    cin >> e;
    E = (Node*)new Node;
    E->data = e;
    E->next = P->next;
    P->next = E;
}
void Delete(Node* L)
{
    int n, e,pan;
    Node* P = L,*q;
    cout << "请输入要删除的位置" << endl;
    cin >> n;
    Search(P, n, pan);
    if (pan == 0)
        return;
    q = P->next;
    e = q->data;
    P->next = q->next;
    delete q;
    cout << "元素 " << e << " 已删除" << endl;
}
void Conver(Node*& L)
{
    Node* p, * q, * r;
    p = L->next;

    q = p->next;
    p->next = NULL;
    while (q)
    {
        r = q->next;
        q->next = p;
        L->next = q;
        p = q;
        q = r;

    }
}
int main()
{
    Node *L;
    Set(L);
    Print(L);
    Insert(L);
    Print(L);
    int e;
    Delete(L);
    Print(L);
    Conver(L);
    cout << "逆置结果为:";
    Print(L);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值