单链表创建、插入和遍历

 

// test15.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include
<iostream>
using namespace std;

template
<class ElemType>//单链表结点
struct LNode{
    ElemType data;
    LNode
* next;
};

/**
ListInsert(L, pos, d)
p=L[pos-1]
node->next=p->next
p->next=node    
*/
template
<class ElemType>
int ListInsert(LNode<ElemType>* L, int pos, ElemType d){
    LNode
<ElemType>* p=L;  //p用于遍历List
    if(pos<=0return -1//只能在头结点(pos=0)之后插入
    for(int i=0;i<pos-1;i++//寻找插入位置的前一个结点
        p=p->next;
    LNode
<ElemType>* node=(LNode<ElemType>*)malloc(sizeof(LNode<ElemType>));
    node
->data=d;
    node
->next=p->next;
    p
->next=node;
    
return 1;
}

template
<class ElemType>
ostream
& operator<<(ostream& out, LNode<ElemType>* L){ //重载<<便于输出LinkList
    LNode<ElemType>* p=L->next;
    
while(p){
        
out<<p->data<<"-->";
        p
=p->next;
    }
    
out<<"NULL";
    
return out;
}

template
<class ElemType> //对单链表初始化
LNode<ElemType>* ListInit(){ 
    LNode
<ElemType>* p=(LNode<ElemType>*)malloc(sizeof(LNode<ElemType>));
    p
->data=-1;
    p
->next=NULL;
    
return p;
}

int main()
{
    LNode
<int>* list=ListInit<int>();
    
for(int i=0;i<10;i++){
        ListInsert(list,i
+1, i*i);
    }
    cout
<<list;
    system(
"pause");
}

posted on 2008-10-22 17:33 deep2 阅读(592) 评论(0)  编辑 收藏 引用 所属分类: 链表


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2008年10月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜