c++急速进阶之链表

来源:互联网 发布:拍照求导数软件 编辑:程序博客网 时间:2024/05/07 16:12

c++急速进阶之链表

  • 代码
//-----------------------------------【程序说明】----------------------------------------------//  程序名称::list链表//  2016年2月 Create by arrstd//  描述:实现链表的基本操作,c++入门式//----------------------------------------------------------------------------------------------#pragma once#ifndef LIST_H#define LIST_H#include<iostream>using namespace std;#define NULL 0struct listnode {    int data = NULL;    listnode *next = NULL;};class list {private:    listnode* head;public:    list() { this->head = new listnode; };    ~list() {};    int backlength();    void show();    void create();    void create(int);    void insert(int n,int number);    void list_delete(int n);};/*返回链表的长度,这里还有一点bug*/int list::backlength()  {    int length = 1;    listnode* q = this->head;    while (1) {        if (q->next != NULL) {            length++;            q = q->next;        }        else break;    }    return length;}/*删除*/void list::list_delete(int n){    listnode *front = NULL , *behind = NULL;    if (n == 1)     {        this->head->data = this->head->next->data;        this->head->next = this->head->next->next;    }    else     {        front = this->head;        behind = this->head;        for (int i = 0; i != n; i++)        {            behind = behind->next;        }        for (int i = 2; i != n; i++)        {            front = front->next;        }        front->next = behind;    }}/*插入*/void list::insert(int n,int number){    listnode *p = new listnode;    listnode *front = NULL , *behind = NULL;    if (n == 1)     {        p->data = this->head->data;        this->head->data = number;        p->next = this->head->next;        this->head->next = p;    }    else    {        p->data = number;        behind = this->head;        front = this->head;        for (int i = 1; i != n; i++)        {            behind = behind->next;        }        for (int i = 2; i != n; i++)        {            front = front->next;        }        front->next = p;        p->next = behind;    }}/*输出链表*/void list::show() {    listnode* q = this->head;    for (int i = 0; i != backlength(); i++)    {        cout << q->data << " ";        q = q->next;    }    cout << endl;}/*创建链表*/void list::create() {    if (this->head->data == NULL) { cin >> this->head->data; }    else {        listnode* p = new listnode;        listnode *q = this->head;        for (int i = 1; i != backlength(); i++)        {            q = q->next;        }        cin >> p->data;        q->next = p;    }}void list::create(int number) {    if (this->head->data == NULL) { this->head->data = number; }    else {        listnode* p = new listnode;        listnode *q = this->head;        for (int i = 1; i != backlength(); i++)        {            q = q->next;        }        p->data = number;        q->next = p;    }}#endif // !LIST_H

c语言的时候也有做过链表,但是很久没碰,所以并不怎么熟悉了,这里着了个最简单的链表,还有太多的缺陷,有机会再修改吧。

0 0