文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>单链表逆置

单链表逆置

时间:2010-09-25  来源:buptstehc




#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    struct node *next;
    int id;
}node;
node *head;

void traverse(node *p)
{
    while(p)
    {
        printf("%d\n", p->id);
        p = p->next;
    }
}

//insert a node in after the head

void insert(node *p)
{
    node *first = head->next;
    
    head->next = p;
    p->next = first;
}

//inverse the list iteratively

node* inverse1(node *p)
{
    node *p1, *p2, *p3;
    
    //return directly if empty list or only one element in the list

    if((p == NULL) || (p->next == NULL))
        return p;
    
    p1 = p;
    p2 = p1->next;
    while(p2)
    {
        p3 = p2->next;
        p2->next = p1;
        p1 = p2;
        p2 = p3;
    }
    
    p->next = NULL;
    head = p1;
    
    return head;
}

//inverse the list recursively

void inverse2(node *cur, node *pre)
{
    if (!cur)
    {
        head = pre;
        return;
    }
        
    inverse2(cur->next, cur);
    cur->next = pre;
}

int main()
{
    node *p;
    int i;
    
    head = (node *)malloc(sizeof(node));
    head->next = NULL;
    head->id = -1;
        
    for(i = 0; i < 5; i++)
    {
        p = (node *)malloc(sizeof(node));
        p->id = i;
        insert(p);
    }
    
    inverse1(head);
    //inverse2(head, NULL);

    traverse(head);
    
    system("pause");
    return 0;
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载