用C++结构实现链表,并对链表进行创建,插入、删除节点等操作。在此程序中,要特别注意链表删除操作时一定要及时清除删除节点所占用的内存,以免发生内存泄露。
InBlock.gif#include <iostream>  
InBlock.gif using namespace std;
InBlock.gif struct node
InBlock.gif{
InBlock.gif     int data;
InBlock.gif    node* next;
InBlock.gif};
InBlock.gif void push(node** headRef, int data)
InBlock.gif{
InBlock.gif    node* newnode= new node;
InBlock.gif    newnode->data=data;
InBlock.gif    newnode->next=*headRef; //实际的表头指针
InBlock.gif    *headRef=newnode;
InBlock.gif}
InBlock.gif void insert(node* &head,node* newLink)
InBlock.gif{
InBlock.gif    node* before;
InBlock.gif    node* current;
InBlock.gif    before=current=head;
InBlock.gif     while(head!=NULL)
InBlock.gif   if(current->data>newLink->data)
InBlock.gif       break;
InBlock.gif   else
InBlock.gif  {
InBlock.gif      before=current;
InBlock.gif      current=current->next;
InBlock.gif  }
InBlock.gif   if(head==current)
InBlock.gif  {
InBlock.gif      current->next=head;
InBlock.gif      head=current;
InBlock.gif  }
InBlock.gif   else
InBlock.gif  {
InBlock.gif      before->next=newLink;
InBlock.gif      newLink->next=current;
InBlock.gif  }
InBlock.gif
InBlock.gif}
InBlock.gif void deleteLink(node** head, int data)
InBlock.gif{
InBlock.gif    node* before,*current,*temp=NULL;
InBlock.gif  before=current=*head;
InBlock.gif     while(current!=NULL)
InBlock.gif   if(current->data!=data)
InBlock.gif  {
InBlock.gif      before=current;
InBlock.gif      current=current->next;
InBlock.gif  }
InBlock.gif   else
InBlock.gif  {
InBlock.gif       if(current!=0)
InBlock.gif      {
InBlock.gif       if(current==*head)
InBlock.gif      {
InBlock.gif    temp=current;   //temp指针用于记录删除节点
InBlock.gif    *head=current->next;
InBlock.gif    before=current->next;
InBlock.gif    current=current->next;
InBlock.gif    delete temp; //释放删除节点的内存空间
InBlock.gif      
InBlock.gif      }
InBlock.gif       else
InBlock.gif      {
InBlock.gif    temp=current;
InBlock.gif    before->next=current->next;
InBlock.gif    current=current->next;
InBlock.gif    delete temp;
InBlock.gif      }
InBlock.gif      }
InBlock.gif  }
InBlock.gif}
InBlock.gif void printLink(node* head)
InBlock.gif{
InBlock.gif    node* pull=head;
InBlock.gif     while(pull!=0)
InBlock.gif    {
InBlock.gif  cout<<pull->data<< "  ";
InBlock.gif  pull=pull->next;
InBlock.gif    }
InBlock.gif    cout<<endl;
InBlock.gif}
InBlock.gif void main( void)
InBlock.gif{
InBlock.gif    node* head=0;
InBlock.gif    node* tail;
InBlock.gif    push(&head,1);
InBlock.gif    tail=head;
InBlock.gif     for( int i=2;i<10;i++)
InBlock.gif    {
InBlock.gif  push(&(tail->next),i);
InBlock.gif  tail=tail->next;
InBlock.gif    }
InBlock.gif    printLink(head);
InBlock.gif    node* newnode= new node;
InBlock.gif    newnode->data=3;
InBlock.gif    newnode->next=NULL;
InBlock.gif    insert(head,newnode);
InBlock.gif    printLink(head);
InBlock.gif    deleteLink(&head,3);
InBlock.gif    printLink(head);
InBlock.gif}  
InBlock.gif