c或者c++ 描述一个 单向链表

zhourenyun 2008-04-11 04:28:11
那位大侠能写一个c++/c的动态分配内存的链表
包括释放内存
赋初值等
...全文
270 24 打赏 收藏 转发到动态 举报
写回复
用AI写文章
24 条回复
切换为时间正序
请发表友善的回复…
发表回复
knowledge_Is_Life 2008-05-01
  • 打赏
  • 举报
回复
有问题请先GOOGLE,BAIDU
Chandler_Bing 2008-04-16
  • 打赏
  • 举报
回复
[Quote=引用 13 楼 hellodudu 的回复:]
引用 9 楼 babyvox1999 的回复:
引用 3 楼 chen_de_sheng 的回复:
额,这么迅速,楼上的。。。


一份好类库 拷贝好带身边 一用好多年...
[/Quote]

哪里找,自己积累?
小一郎 2008-04-15
  • 打赏
  • 举报
回复
#include "iostream.h"

class Link{
public:
int element;
Link *next;
Link(const int& elemval,Link* nextval=NULL)
{
element=elemval;
next=nextval;
}
Link(Link* nextval=NULL)
{
next=nextval;
}
};
class LLIST{
private:
Link *head;
Link *tail;
Link *fence;
int leftcnt;
int rightcnt;
void init()
{
fence=tail=head=new Link;
leftcnt=rightcnt=0;
}
void removeall()
{
while(head!=NULL)
{
fence=head;
head=head->next;
delete fence;
}
}
public:
LLIST(int size=100)
{
init();
}
~LLIST()
{
removeall();
}
void clear()
{
removeall();
init();
}
int insert( int&);
int append( int&);
int remove( int&);
void setstart()
{
fence=head;
rightcnt+=leftcnt;
leftcnt=0;
}
void setend()
{
fence=tail;
leftcnt+=rightcnt;
rightcnt=0;
}
void prev();
void next()
{
if(fence!=tail)
{
fence=fence->next;
rightcnt--;
leftcnt++;
}
}
int setpos(int pos);
int getvalue(int& it)
{
if(rightcnt==0)
{
return 0;
}
it=fence->next->element;
return 1;
}
void print() ;
};

int LLIST::insert( int& item)
{
fence->next=new Link(item,fence->next);
if(tail==fence)
{
tail=fence->next;
}
rightcnt++;
return 1;
}
int LLIST::append( int& item)
{
tail=tail->next=new Link(item,NULL);
rightcnt++;
return 1;
}
int LLIST::remove(int& it)
{
if(fence->next==NULL)
return 0;
it=fence->next->element;
Link* ltemp=fence->next;
fence->next=ltemp->next;
if(tail==ltemp)
{
tail=fence;
}
delete ltemp;
rightcnt--;
return 1;
}
void LLIST::prev()
{
Link* temp=head;
if(fence==head) return;
while(temp->next!=fence)
{
temp=temp->next;
}
fence=temp;
leftcnt--;
rightcnt++;
}
int LLIST::setpos(int pos)
{
if((pos<0)||(pos>leftcnt+rightcnt))
{
return 0;
}
fence=head;
for(int i=0;i<pos;i++)
{
fence=fence->next;
}
return 1;
}
void LLIST::print()
{
Link* temp=head;
cout<<"<";
while(temp!=fence)
{
cout<<temp->next->element<<" ";
temp=temp->next;
}
cout<<"|";
while(temp->next!=NULL)
{
cout<<temp->next->element<<" ";
temp=temp->next;
}
cout<<">"<<endl;
}
int search(LLIST& L,int K)
{
int it;
for(L.setstart();L.getvalue(it);L.next())
{
if(K==it) return 1;
}
return 0;
}
void main()
{
int control,item,it,K;
LLIST L;
while(1)
{
cout<<"please input the control command:\n"
<<"1.clear"<<endl
<<"2.insert"<<endl
<<"3.append"<<endl
<<"4.delete"<<endl
<<"5.search"<<endl
<<"0.exit"<<endl;
cin>>control;
if(control<0||control>5)
{
cout<<"error!please input a valid command."<<endl;
}
if(control==0)
{
cout<<"exit\n";
break;
}
switch(control){
case 1:cout<<"clear\n";
L.clear();
L.print();
break;
case 2:cout<<"insert"<<endl<<"input the number for insert:";
cin>>item;
L.insert(item);
L.print();
break;
case 3:cout<<"append"<<endl<<"input the number for append:";
cin>>item;
L.append(item);
L.print();
break;
case 4:cout<<"delete\n";
if(L.remove(it))
cout<<"delete successfully\n";
else
cout<<"error!";
L.print();
break;
case 5:cout<<"search"<<endl<<"input the number for search:";
cin>>K;
if(search(L,K))
cout<<K<<"in the list\n";
else
cout<<K<<"not in the list\n";
L.print();
break;

}
}
cout<<"the reslut is:\n";
L.print();

}
lsmdiao0812 2008-04-14
  • 打赏
  • 举报
回复
也写了一个

class ListNode{
friend class List;
int data;
ListNode *next;
public:
ListNode(){next=NULL;}
ListNode(int data,ListNode *next):data(data),next(next){}
};

class List{
ListNode *Head;
public:
List()
{
Head=new ListNode();
Head->next=NULL;
}

void InsertPreNode(const int &data);
void InsertEndNode(const int &data);
void InsertNode(const int &index,const int &data);
void DeleteNode(const int &index);

void PrintList()const;
};

void List::InsertPreNode(const int &data)//插入节点
{
ListNode *p=NULL;
p=new ListNode();

p->data=data;
p->next=NULL;

p->next=Head->next;
Head->next=p;
}

void List::InsertEndNode(const int &data)//插入节点
{
ListNode *p=NULL;
p=new ListNode();

p->data=data;
p->next=NULL;

ListNode *q=NULL;
q=Head;
while(q->next!=NULL)
q=q->next;

q->next=p;
}

void List::InsertNode(const int &index,const int &data)//插入节点
{
assert(index>0);

ListNode *p,*q;
q=Head;
p=Head->next;
for(int i=1;i<index&&p!=NULL;i++)
{
q=p;
p=p->next;
}

ListNode *NewNode=new ListNode();
NewNode->data=data;
NewNode->next=NULL;

NewNode->next=p;
q->next=NewNode;
}

void List::DeleteNode(const int &index)//删除节点
{
ListNode *p,*q;
p=Head->next;
q=Head;

for(int i=1;i<index&&p!=NULL;i++)
{
q=p;
p=p->next;
}
if(p!=NULL)
q->next=p->next;
}

void List::PrintList()const//打印
{
ListNode *p;
p=Head->next;
while(p!=NULL)
{
printf("%d-",p->data);
p=p->next;
}
}

int main(array<System::String ^> ^args)
{
List list;

list.InsertPreNode(4);
list.InsertPreNode(2);
list.InsertPreNode(8);
list.InsertEndNode(5);
list.InsertEndNode(1);
list.InsertNode(2,10);
list.PrintList();
printf("\n");
list.DeleteNode(1);
list.PrintList();
printf("\n");
list.DeleteNode(10);
list.PrintList();
getchar();
return 1;
}

shaoze5 2008-04-14
  • 打赏
  • 举报
回复
那你可以在csdn里搜索一下的,这里面说道链表的地方多的很。
有很多帖子你也可以再借鉴一下滴!
zhourenyun 2008-04-14
  • 打赏
  • 举报
回复
我写了 不太理想 所以问一下大家 开阔下思路。
linuxsir2007 2008-04-14
  • 打赏
  • 举报
回复
不错,mark,以后方便查找
hoya5121 2008-04-13
  • 打赏
  • 举报
回复
http://blog.csdn.net/hoya5121/archive/2008/04/07/2257635.aspx
hoya5121 2008-04-13
  • 打赏
  • 举报
回复
#ifndef SIMPLELIST_H
#define SIMPLELIST_H

//#include <windows.h>

template <class T> class SimpleListNode ...{

public:
T &get() ...{ return object; };
void set(T &object) ...{ this->object = object; };

SimpleListNode<T> *getNext() ...{ return nextNode; };
void setNext(SimpleListNode<T> *nextNode) ...{ this->nextNode = nextNode; };

private:
T object;
SimpleListNode<T> *nextNode;
};

template <class T> class SimpleList ...{

public:
// Constructor
SimpleList() ...{
headNode = new SimpleListNode<T>;
headNode->setNext(NULL);

currentNode = NULL;
size = 0;
};

// Destructor
~SimpleList() ...{

SimpleListNode<T> *pointerToDelete, *pointer = headNode;

while (pointer != NULL) ...{
pointerToDelete = pointer;
pointer = pointer->getNext();
delete pointerToDelete;
}
};

T &get() ...{

if (currentNode == NULL)
start();

return currentNode->get();
};

void add(T &addObject) ...{

SimpleListNode<T> *newNode = new SimpleListNode<T>;

newNode->set(addObject);

newNode->setNext(headNode->getNext());
headNode->setNext(newNode);

size++;
};

void remove() ...{

lastCurrentNode->setNext(currentNode->getNext());

delete currentNode;

currentNode = lastCurrentNode;

size--;
};

void start() ...{
lastCurrentNode = headNode;
currentNode = headNode;
};

bool next() ...{

// If the currentNode now points at nothing, we've reached the end
if (currentNode == NULL)
return false;

// Update the last node and current node
lastCurrentNode = currentNode;
currentNode = currentNode->getNext();

// If currentNode points at nothing or there is nothing added, we can immediately return false
if (currentNode == NULL || size == 0)
return false;
else
return true;
};

int getSize() ...{ return size; };

private:
int size;
SimpleListNode<T> *headNode;
SimpleListNode<T> *currentNode, *lastCurrentNode;
};

#endif
hellodudu 2008-04-12
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 babyvox1999 的回复:]
引用 3 楼 chen_de_sheng 的回复:
额,这么迅速,楼上的。。。

[/Quote]
一份好类库 拷贝好带身边 一用好多年...
zhourenyun 2008-04-12
  • 打赏
  • 举报
回复
谢谢 各位 今天爬山去
过了周一仔细学习下各位大虾的代码.
谢谢各位的热心.
Gavin001 2008-04-12
  • 打赏
  • 举报
回复
建议楼主尽量自己写
xiaoZhang888 2008-04-12
  • 打赏
  • 举报
回复
谢谢各位啦 这里真好啊 哈哈 受益匪浅!!
Yoon_EunHae 2008-04-11
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;

template <class T>
class LinkList{
private:
struct LNode{
T data;
struct LNode *next;
};
LNode *hlist;
static int len;
//特别注意指针的移动
public:
LinkList();
~LinkList();
bool IsEmpty()const;
void InsFirst(const T & e); //插入的结点作为头结点
void InsLast(const T & e); //在链尾插入
int GetLength(); //返回链表长度
bool DelFirst(); //删除头结点
bool InsAfter(const T & e,int n); //在第n个结点后插入
bool DelIndex(int n); //删除指定的索引结点
void TraverseList(); //遍历整个表

};

template <class T>
int LinkList<T>::len=0;

template <class T>
LinkList<T>::LinkList(){
hlist=NULL;
}

template <class T>
LinkList<T>::~LinkList(){
while(!IsEmpty()){
cout<<"Destroy list,Destroy list length is: "<<len<<endl;
DelFirst();
system("pause");
}
exit(0);
cout<<"Destroy list,Destroy list length is: "<<len<<endl;
system("pause");
}

template <class T>
bool LinkList<T>::IsEmpty()const{
return len==0;
}

template <class T>
void LinkList<T>::InsFirst(const T &e){
LNode *p=new LNode;
p->data=e;
if(len==0){
p->next=NULL;
hlist=p;
}
else{
p->next=hlist;
hlist=p;
}
len++;
}

template <class T>
void LinkList<T>::InsLast(const T &e){
if(IsEmpty())
InsFirst(e);
else{
LNode *p=new LNode;
p->data=e;
LNode *temp=hlist;
while(temp->next!=NULL)
temp=temp->next;
p->next=temp->next;
temp->next=p;
len++;
}

}

template <class T>
bool LinkList<T>::InsAfter(const T & e,int n){
if(n<0||n>len)
return false;
if(IsEmpty()) //如果链表为空 作为头结点插入
InsFirst(e);
else{
LNode *p=new LNode;
p->data=e;
LNode *temp=hlist;
while(n-1>0){
n--;
temp=temp->next;
}
p->next=temp->next;
temp->next=p;
len++;
}
return true;
}

template <class T>
bool LinkList<T>::DelIndex(int n){
if(IsEmpty()||n<0||n>len)
return false;
else{
LNode *temp=hlist;
while(n-2>0){
temp=temp->next;
n--;
}
LNode *p=temp->next;
temp->next=p->next;
delete p;
len--;
}
return true;
}



template <class T>
int LinkList<T>::GetLength(){
return len;
}

template <class T>
bool LinkList<T>::DelFirst(){
LNode *p=hlist;
if(IsEmpty())
return false;
else{
hlist=p->next;
delete p;
len--;
}
}

template <class T>
void LinkList<T>::TraverseList(){
LNode *p=hlist;
while(p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}

int main(){
LinkList<int> L;
L.InsFirst(3);
L.InsFirst(2);
L.InsFirst(5);
L.InsFirst(1);
L.InsLast(4);
L.InsLast(6);
cout<<"Now , Linklist all mumber is: "<<endl;
L.TraverseList();
cout<<"The Linklist length is: "<<L.GetLength()<<endl;
cout<<"Delete the fifths mumber."<<endl;
L.DelIndex(2);
cout<<"Now , Linklist all mumber is: "<<endl;
L.TraverseList();
cout<<"Insert '5'."<<endl;
L.InsAfter(5,4);
cout<<"The Linklist length is: "<<L.GetLength()<<endl;
L.TraverseList();

return 0;
}

Supper_Jerry 2008-04-11
  • 打赏
  • 举报
回复
#include<iostream.h>

struct node{
int data;
node *next;
};

node* Listcreat() //´´½¨Á´±í
{
node *head,*n,*tail;
int a;
head=NULL; //¿ÕÁ´
cout<<"ÇëÊäÈëÊý¾Ý£¨0±íʾ½áÊø£©:";
for(cin>>a;a!=0;cin>>a)
{
n=new node;
n->data=a;
n->next = NULL;
if(!head) tail=head=n;
else tail->next=n,tail=n;
}
if(head) tail->next=NULL;
return head;
}

void clearlist(node *list)//Èç¹ûÁ´±í²»ÊÇÓÐÐòÇÒÊÇÉýÐòµÄ£¬Ôò½«Á´±í±»ËùÓнáµãɾ³ý
{
node*head,*p;
head=list;
while(head)
{
p=head;head=head->next;
delete p;
}
cout<<"ÎÞЧÊý¾ÝÇå³ý³É¹¦£¡\n";
}

int panduan(node *List)//ÅжÏÁ´±íÊDz»ÊÇÓÐÐò£¨ÉýÐò£©µÄÁ´±í
{
node *head,*p;
head=List;
if(head)
{
p=head->next;
for(head;head->next!=NULL;head=head->next,p=head->next)
for(p;p!=NULL;p=p->next)
if(p->data<head->data)
return 0;
if(!head->next)
return 1;
}
else
return 0;
return 1;
}

void print(node*List)//Êä³öÁ´±íÉÏËùÓеÄÊý¾ÝÔªËØ
{
node *p;
p=List;
while(p)
{ cout<<p->data<<'\t';p=p->next; }
cout<<endl;
}

void DelList(node *p)
{
node *q = p;
while(p)
{
q = p->next;
delete p;
p = q;
}
}
void combin (node *La,node *Lb) //ʵÏÖÁ´±íLa,LbµÄ¹é²¢,¹é²¢ºóΪLc
{
node *pa,*pb,*pc,*Lc;
pa=La;
pb=Lb;

pc = new node;
pc->next = NULL;
Lc=pc; //¹é²¢ºóµÄÁ´±íµÄÍ·½áµãÖ¸ÏòÁ¬±íLaµÄÍ·½áµã
while(pa&&pb)
{
if(pa->data<=pb->data)
{
pc->next=pa;
pa=pa->next;
}
else
{
pc->next=pb;
pb=pb->next;
}
pc = pc->next;
}

if(pa)
pc->next=pa;//²åÈëÊ£ÓàµÄ½áµã
else
pc->next=pb;//²åÈëÊ£ÓàµÄ½áµã
pc = Lc;
Lc = Lc->next;
delete pc;
print(Lc);//Êä³ö¹é²¢ºóµÄ¼¯ºÏÔªËØ
DelList(Lc);
}



void main()
{
node *List_La = NULL, *List_Lb = NULL;

cout<<"¼¯ºÏA"<<endl;
List_La=Listcreat();//´´½¨Á´±íList_La´æ´¢¼¯ºÏAµÄÔªËØ
while(!panduan(List_La))
{
cout<<"ÊäÈëµÄÊý¾ÝÎÞЧ£¬ÇëÊäÈëÓÐÐòµÄ¼¯ºÏÔªËØ!\n";
clearlist(List_La);
List_La=Listcreat();//ÅжϺóÖØÐÂÊäÈ뼯ºÏÔªËØ
}

cout<<"¼¯ºÏB"<<endl;
List_Lb=Listcreat();//´´½¨Á´±íList_La´æ´¢¼¯ºÏAµÄÔªËØ
while(!panduan(List_Lb))
{
cout<<"ÊäÈëµÄÊý¾ÝÎÞЧ£¬ÇëÊäÈëÓÐÐòµÄ¼¯ºÏÔªËØ!\n";
clearlist(List_Lb);
List_Lb=Listcreat();
}
cout<<"¾­¹ý¹é²¢ºó£¡";
combin(List_La,List_Lb);
}
两个链表归并排序,乱码是中文,你可以忽略不计
babyvox1999 2008-04-11
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 chen_de_sheng 的回复:]
额,这么迅速,楼上的。。。
[/Quote]
zhourenyun 2008-04-11
  • 打赏
  • 举报
回复
好像都没有内存分配成功的 判断
chenzhp 2008-04-11
  • 打赏
  • 举报
回复
递归创建链表和释放
#include "stdafx.h"
#include <stdio.h>
#include <malloc.h>
typedef struct data
{
int Data;
struct data *next;
}str;

void Create(str **p)
{
*p=(str*)malloc(sizeof(str));
printf("input the data:");
scanf("%d",&((*p)->Data));
if((*p)->Data!=0)
{
Create(&((*p)->next));
}
else
{
p=NULL;
return;
}
}
void FreeList(data* pList) //释放链表
{
data* temp = pList;
while(temp->Data != 0)
{
pList=pList->next;
free(temp);
temp = NULL;
temp=pList;


}
}
void main()
{
data *p;
Create(&p);

FreeList(p);
}
Inhibitory 2008-04-11
  • 打赏
  • 举报
回复
#include <iostream>
#include <cstdio>
#include <ctime>
#include <cmath>
#include <cstdlib>

using namespace std;

template<typename T>
class List {
public:
List();
List(T);
~List();
void addToFront(T data); // 把数据加到链表头
void add(T data); // 把数据加到链表尾
void erase(T); // 删除指定的数据
void reverse(); // 返转链表
void sort();
void sort(bool); // 对链表进行排序,指定排序方式
void insert(T); // 把数据插入链表,按链表
bool contains(T) const; // 链表是否包含指定的数据
void print() const; // 打印出链表的元素

private:
// 链表中的结点的结构
struct Node{
T data;
Node* next;
};

Node* const head; // 头结点,能够简化算法,何乐而不用!
bool isIncrease; // 是按升序排列还是按降序排列链表.
};

template<typename T>
List<T>::List(): head(new Node()) { // 为链表头结点分配空间.
head->next = NULL;
this->isIncrease = true;
}

template<typename T>
List<T>::List(T data): head(new Node()) {
head->next = NULL;
this->add(data);
this->isIncrease = true;
}

template<typename T>
List<T>::~List() {
Node* temp;
Node* pre = head;

int count = 0;
while (pre != NULL) {
temp = pre->next;
delete pre;
pre = temp;
//cout << "Destructor times: " << ++count << endl;
}
}

template<typename T>
void List<T>::addToFront(T data) {
Node* temp = new Node();
temp->data = data;
temp->next = head->next;
head->next = temp;
//cout << temp->data << endl;
}

template<typename T>
void List<T>::add(T data) {
Node* tail = head;

// 找到链表最后一个结点.
while (tail->next != NULL) {
tail = tail->next;
//cout << "tail" << endl;
}

Node* temp = new Node();
temp->data = data;
temp->next = NULL;
tail->next = temp;
}

template<typename T>
void List<T>::erase(T data) {
Node* temp = head->next;
Node* pre = NULL;

// 找到指定数据的结点,如果temp == NULL,如没找到.
while (temp != NULL && temp->data != data) {
pre = temp;
temp = temp->next;
}

// temp != NULL,说明找到.
if (temp != NULL) {
pre->next = temp->next;
delete temp;
temp = NULL;
}
}

template<typename T>
void List<T>::reverse() {
if (NULL == head->next) return;

Node* temp = head->next;
Node* post = temp->next;
head->next = NULL;

while (temp != NULL) {
temp->next = head->next;
head->next = temp;
temp = post;
if (post != NULL) {
post = post->next;
}
}
}

template<typename T>
void List<T>::sort() {
this->sort(true);
}

template<typename T>
void List<T>::sort(bool isIncrease) {
this->isIncrease = isIncrease;
// 如果链表除头结点或者只有一个有交数据结点,则不用排序.
if ((NULL == head->next) || (NULL == head->next->next)) {
return;
}

// 链表有两个或两个以上有效数据结点,则排序.
Node* temp = head->next->next; // temp为第二个结点
head->next->next = NULL;
Node* post = temp->next; // post为temp的下一结点
Node* t = NULL; // 与temp进行比较,在链表中找到合适位置的结点指针.

if (isIncrease) { // 按升序排序, 用插入法排序.
while (temp != NULL) {
t = head;
//**这里的取&&的顺序不能反,否则出错.
// 找到比temp大的结点t,即把temp插入t的前面.
while ((t->next != NULL) && (t->next->data < temp->data)) {
t = t->next;
}
temp->next = t->next;
t->next = temp;
//cout <<"sort" << endl;
temp = post;
if (post != NULL) {
post = post->next;
}
}
} else { // 按降序排序
while (temp != NULL) {
t = head;
while ((t->next != NULL) && (t->next->data > temp->data)) {
t = t->next;
}
temp->next = t->next;
t->next = temp;
//cout <<"sort" << endl;
temp = post;
if (post != NULL) {
post = post->next;
}
}
}
}

template<typename T>
void List<T>::insert(T data) {
Node* node = new Node();
node->data = data;

Node* temp = head;
if (this->isIncrease) { // 按升序排列的时候的顺序插入结点.
// 找到比node大的结点,插入node在其前面.
while (temp->next != NULL && node->data > temp->next->data) {
temp = temp->next;
}
node->next = temp->next;
temp->next = node;
} else {
while (temp->next != NULL && node->data < temp->next->data) {
temp = temp->next;
}
node->next = temp->next;
temp->next = node;
}
}

template<typename T>
bool List<T>::contains(T data) const {
Node* temp = head->next;

while (temp != NULL) {
if (temp->data == data) {
return true;
}
temp = temp->next;
}

return false;
}

template<typename T>
void List<T>::print() const {
Node* temp = head;

cout << "[";
if (temp->next != NULL) {
// 打印结点直到倒数第二个.
while (temp->next->next != NULL) {
cout << temp->next->data << ", ";
temp = temp->next;
}
}
if (temp->next != NULL) {
// 打印倒数第一个结点
cout << temp->next->data;
}
cout << "]" << endl;
}

int main() {
List<int> lst(23);

for (int i = 11; i > 0; i--) {
//lst.add(i);
}

for (int i = 0; i < 21; i++) {
//lst.add(i);
}

srand(time(0));
for (int i = 0; i < 10; i++) {
lst.add(rand() % 150);
}

lst.print();

//lst.erase(15);
//lst.erase(9);
lst.sort(false);
lst.print();

lst.insert(55);
lst.print();

lst.sort(true);
lst.insert(100);
lst.print();

cout << lst.contains(55);

return 0;
}


以前写的程序, 可以参考一下.

zhourenyun 2008-04-11
  • 打赏
  • 举报
回复
哇 stl 牛
加载更多回复(4)

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧