单链表的生成,插入,删除,反向

// shuangshuang.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<stdio.h>
#include<malloc.h>
#include<iomanip>
//#include"myheader.h"
using namespace std;





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

bool init(node*& head,int darry[],int len)//初始化一个链表,链表载入数组darry的数据,len为长度
{
    if(darry == NULL)
        return false;

    head =(node*)malloc(sizeof(node));
    node *p =head;
    

    if(head==0)
    {
        cout<<"have not got any storage";
    }

    p->data=darry[0];

    for(int i=1;i<len;i++)
    {

        node *pnext =(node*)malloc(sizeof(node));
        pnext->data=darry[i];
        p->next=pnext;
        p=p->next;
    }

    p->next=NULL;
}

void DisplayList(node* head)
{
    cout<<endl;

    while(head!=NULL)
    {
        cout<<head->data<<endl;
        head=head->next;
    }
}


int length(node* head)
{
    if(head == NULL)
        return 0;
    
    int i=0;
    while(head!=NULL)
    {
        head=head->next;
        i++;
    }
    return i;
}

node* del(node*& head,int num)//删除链表中value为num的结点
{
    node* p = head;
    node* psave = p;
    while(p->data!=num && p->next !=NULL)
    {
        psave = p;
        p=p->next;
    }

    if(p == head)//如果是删除头结点的话
    {

        head=p->next;
        free(p);
        return head;
    }
    if( p->data == num)
    {
        psave->next = p->next;
        free(p);
    }
    else
    {
        cout<<"there is no "<<num<<"in the list"<<endl;
    }

    return head;

}

bool insertList(node*& head , int num)//把num插入链表(按照data的大小)
{
    node* p = head;
    node* inp=(node*)malloc(sizeof(node));
    inp->data = num;

    if(inp == NULL)
    {
        cout<<"can`t get any memory";
        return false;//没有插入返回错误
    }

    if(num<head->data)
    {
        inp->next=head;
        head=inp;
        return true;
    }
    while(p->next!=NULL && p->next->data < num)
    {
        p=p->next;
    }


    inp->next = p->next;
    p->next=inp;

    return true;


}

node* reverseRecursive(node* head)
{
    if( head == NULL || head->next==NULL)
        return head;

    node* pr=reverseRecursive(head->next);
    head->next->next=head;
    head->next=NULL;

    return pr;
}

node* reverse(node* head) //非嵌套版反转链表
{
    if( head == NULL || head->next==NULL)
        return head;

    node* p=head;
    node* pre = NULL;
    node* temp;


    while(p!=NULL)
    {
    temp=p->next;
    p->next=pre;
    pre=p;
    p=temp;
    }

    return pre;
}

int main()
{
    node *head = NULL;
    int thedata[]={11,12,13,24,35};

    init(head,thedata,5);

    del(head,1312);
    DisplayList(head);

    insertList(head,20);
    DisplayList(head);

    head=reverse(head);
    DisplayList(head);
    cout<<"length:"<<length(head);
}

 

posted @ 2014-03-28 11:13  joey周琦  阅读(461)  评论(0编辑  收藏  举报