Chinaunix首页 | 论坛 | 博客
  • 博客访问: 288605
  • 博文数量: 148
  • 博客积分: 4365
  • 博客等级: 上校
  • 技术积分: 1566
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-05 21:38
文章分类
文章存档

2014年(2)

2013年(45)

2012年(18)

2011年(1)

2009年(54)

2008年(28)

我的朋友

分类: C/C++

2009-09-04 22:28:35

单链表,有点问题,头结点,头指针

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <malloc.h>
using namespace std;

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

void init(Node **head){
    *head=(Node *)malloc(sizeof(Node));
    if(*head==NULL)
        exit(-1);
    cout<<"create a head"<<endl;
    printf("%x ,*head:%x \n",head,*head);
    (*head)->next=NULL;
    (*head)->data=0;
}

void destroy(Node * head){
    if(head==NULL)
        return;
    else
    {
        Node * q =head;
        while(head!=NULL)
        {
            head=head->next;
            free(q);
            cout<<"free a node !!"<<endl;
            q=head;
        }
    }
}

int length(Node *head){
    Node *p =head;
    if(p==NULL)
    {
        cout<<"exit from lenth()\n";
        exit(-1);
    }
    int i=0;
    while(p->next!=NULL)
    {
        p=p->next;
        i++;
    }
    cout<<"length is :"<<i<<endl;
    return i;

}

void insert(Node *head,int i,int data){
    if(head==NULL)
        {
        printf("%x\n",head);
        cout<<"exit from insert\n";
        exit(-1);
        }
    Node * p=head;

    while((--i)>0)
        p=p->next;

    Node *q=(Node *)malloc(sizeof(Node));
    if(q==NULL)
        exit(-1);

    q->data=data;
    q->next=p->next;
    p->next=q;

}

void del(Node *head,int i){
    if(i>length(head))
        exit(-1);
    Node *p=head;
    while((--i)>0)
    {
        p=p->next;
    }
    Node *q =p->next;
    p->next=q->next;
    free(q);
    cout<<"del a node !!"<<endl;
}

void traverse(Node *head){
    if(head==NULL)
        exit(-1);
    Node *p=head;
    int i=0;
    while(p->next!=NULL)
    {
        p=p->next;
        i++;
        cout<<" Node : "<<i<<" data : "<<p->data<<endl;
    }
}

void reverse(Node *head){
    Node *p=head->next,*q=p->next;
    while(q!=NULL)
    {
        
    }
}

int main(void) {

    Node *mylist=NULL;
    init(&mylist);

    for(int i=0;i<=3;i++)
        insert(mylist,i+1,i+1);
    cout<<"after insert\n";

    traverse(mylist);
//    del(mylist,3);

//    traverse(mylist);

    destroy(mylist);
    puts("Hello World!!!");
    return EXIT_SUCCESS;
}

阅读(324) | 评论(0) | 转发(0) |
0

上一篇:c++中参数入栈顺序

下一篇:vim 插件

给主人留下些什么吧!~~