不想忘却
idleness
全部博文(52)
2010年(1)
2009年(24)
2008年(27)
xszghl
lx131411
dixin01
cutrain2
feiyelov
tringger
干扰弹
chendian
HJonny
分类: C/C++
2009-08-24 11:31:23
#ifndef BASEDEFINE_H_INCLUDED #define BASEDEFINE_H_INCLUDED typedef int Elem; typedef struct tagNode { Elem element; struct tagNode* next; } Node,*Linklist; Linklist create(); void destroy(Linklist &L); bool isEmpty(Linklist L); int getLength(Linklist L); bool insert(Linklist L,Elem e,int pos=0); void deletenode(Linklist L,int pos); void visitall(Linklist L); #endif // BASEDEFINE_H_INCLUDED
#include <iostream> #include "basedefine.h" using namespace std; Linklist create() //建立空表 { Linklist L; if((L =(Linklist) malloc(sizeof(Node)))==NULL) cout<<"ERROR"<<endl; L->element = 0; L->next= NULL; return L; } void destroy(Linklist &L) { if(L==NULL) { cout<<"Null List"<<endl; return; } Node* pre=L; Node* now; while((now=pre->next)!=NULL){ free(pre); pre = now; } free(now); L=NULL; } bool isEmpty(Linklist L) { if(L==NULL) { cout<<"Null List"<<endl; return true; } if(L->next==NULL) return true; return false; } int getLength(Linklist L) { if(isEmpty(L)) return 0; int i; Node* node=L; for(i=0;node->next!=NULL;i++) node = node->next; return i; } bool insert(Linklist L,Elem e,int pos)//在pos位置后插入e,默认在头节点后 { if(L==NULL) { cout<<"Null List"<<endl; return false; } int i=0; Node* tmp; Linklist pre=L; if(pos<0){ cout<<"Wrong position"<<endl; return false; } while(pre->next!=NULL && i<pos) { i++; pre = pre->next; } if(i==pos) { tmp = (Node*)malloc(sizeof(Node)); if(tmp==NULL) return false; tmp->element = e; tmp->next = pre->next; pre->next = tmp; }else //在末尾了 if(pos==i+1) { //刚好在末尾插入 tmp = (Node*)malloc(sizeof(Node)); if(tmp==NULL) return false; tmp->element = e; tmp->next = NULL; pre->next = tmp; }else { cout<<"Wrong position"<<endl; return false; } return true; } void deletenode(Linklist L,int pos) { if(pos>getLength(L) || pos<1 || L==NULL) return; int i; Node* pre=L; for(i=0;i<pos-1;i++) //获得pos前面那个元素的指针 pre = pre->next; Node* posnode=pre->next; if(posnode->next==NULL) { //刚好是删除尾元素 pre->next=NULL; free(posnode); }else { pre->next = posnode->next; free(posnode); } } void visitall(Linklist L) //遍历链表 { if(L==NULL) return; Node* p=L; while(p->next!=NULL) { p=p->next; cout<<p->element<<endl; } } int main() { Linklist L1=NULL; L1=create(); insert(L1,2); insert(L1,6); insert(L1,7); //destroy(L1); insert(L1,28); visitall(L1); cout<<"Length is "<<getLength(L1)<<endl; deletenode(L1,2); visitall(L1); cout<<"Length is "<<getLength(L1)<<endl; destroy(L1); deletenode(L1,3); visitall(L1); cout<<"Length is "<<getLength(L1)<<endl; return 0; }
上一篇:终于解了n皇后问题(二)
下一篇:ctype中判断类型的实现
登录 注册