天之道

享受编程的乐趣。
posts - 118, comments - 7, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

链表节点数

Posted on 2012-08-17 01:43 hoshelly 阅读(265) 评论(0)  编辑 收藏 引用 所属分类: ProgrammingDS && Algorithm
编写一个返回循环链表中节点数的函数

实现代码如下:

#include<stdio.h>
#include<stdlib.h>
typedef struct node *link;
struct node{ int item; link next; };

int node_number(link p,int n)
{
    int count=0,i;
    for(i=0;i<n-1;i++)
    {
        p=p->next;
    }
    while(p->item)
    {
        p->item=0;
        p=p->next;
        count++;
    }
    return count;
}

int main()
{
    
    int i,N;
    link t=(link)malloc(sizeof(node));
    t->item=1;
    t->next=t;
    link x=t;
    for(i=2;i<=10;i++)
    {
        x = (x->next= (link)malloc(sizeof(node)));
        x->item=i;
        x->next=t;
    }
    printf("Please input the order of node: ");
    scanf("%d",&N);
    printf("total number of nodes is: %d\n",node_number(t,N));
    return 0;
}

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理