2.4-其它运算在单链表上的实现

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

#include 
"stdafx.h"
#include 
<iostream.h>
#include 
<malloc.h>

typedef 
struct node * pointer;
struct node
{
    
int data;
    pointer next;
}
;
typedef pointer lklist;
lklist head
=NULL;                        //表头

//建表,只做了第二种建表的算法,第一种书上只作为引例,且算法为O(n2),所以呼略不做了
lklist create_lklist2()
{
    
int x=0;
    head
=(lklist)malloc(sizeof(node));
    lklist p
=head;
    cout
<<"请输入数据项的值,-1结束";
    cin
>>x;
    
    
while(x!=-1)
    
{
        p
->next=(lklist)malloc(sizeof(node));
        p
->next->data=x;
        p
=p->next;
        cout
<<"请输入数据项的值,-1结束";
        cin
>>x;
    }

    p
->next=NULL;
    
return head;
}


//删除重复结点
void purge_lklist(lklist head)
{
    lklist p
=head->next;
    
while(p!=NULL)
    
{
        lklist q
=p;
        
//单链表的做删除操作时,工作结点指向待删的前驱结点
        while(q->next!=NULL)
        
{
            
if (q->next->data==p->data)
            
{
                lklist r
=q->next;
                q
->next=r->next;
                free(r);
            }

            
else
            
{
                q
=q->next;
            }

        }

        p
=p->next;
    }

}


//显示
void display(lklist head)
{
    lklist p
=head;
    
int i=0;
    p
=p->next;                //指向第一个结点
    while(p!=NULL)
    
{
        i
++;
        cout
<<""<<i<<"个元素的值为:"<<p->data<<endl;
        p
=p->next;
    }

}

int main(int argc, char* argv[])
{
    
    
char * error=NULL;
    pointer p
=NULL;
    
int i=0;
    head
=create_lklist2();
    cout
<<"初始化的表为:"<<endl;
    display(head);
    purge_lklist(head);
    cout
<<"删除重复项后的表为:"<<endl;
    display(head);
    
return 0;
}

posted @ 2007-06-25 09:12  吴东雷  阅读(211)  评论(0编辑  收藏  举报