您的位置:首页 > 其它

链表转置实现

2013-03-03 23:06 176 查看
链表转置功能实现,不足之处 ;还请指正

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

typedef  struct Listnode
{
int  nodedata;
struct Listnode*  next;
}Listnode, *pListnode;

//create list
//return value   the number of node created
//param  the head of the listnode

int  CreateListnode(pListnode head, int nodenumber)
{
int ret = 0;
if(NULL == head)
{
return ret;
}

int  input = 0;
Listnode*  front = NULL;
Listnode*  rear = head;              //conect

for(int i = 0; i < nodenumber; i++)
{
front = (Listnode*)malloc(sizeof(Listnode));
if(NULL != front)
{
scanf("%d", &input);
front->nodedata = input;
front->next = NULL;
}

rear->next = front;          //append
rear = rear->next;
++ret;
}
return ret;
}
bool Traversallist(pListnode head)
{
bool ret = false;
if(NULL == head)
{
return ret;
}
Listnode*  p = head->next;
while(p)
{
printf("     %d", p->nodedata);
p = p->next;
}
printf("\n");
ret = true;
return ret;
}
bool ConvertList(pListnode head)
{
bool ret = false;
if(NULL == head)
{
return ret;
}
Listnode*  rear = head->next;
Listnode*  front = head->next->next;            //init the ptr
Listnode*  p = front;

if(NULL == p)                                   //only one element
{
ret = true;
return ret;
}

rear->next = NULL;                              //disconnect the list
while(NULL != p)                                //get the current element
{
front = front->next;                    //insert the element
head->next = p;
p->next = rear;
rear = p;
p = front;
}
ret = true;
return ret;
}
int  releaseListnode(Listnode*  head)
{
int ret = 0;

Listnode* rear = head->next;
Listnode* front = head->next;

while(NULL != rear)
{
front = front->next;
free(rear);
rear = NULL;
rear = front;
++ret;
}
printf("The release number of element is %d\n", ret);
return ret;
}
int main()
{
printf("sizeof(Listnode) == %d\n", sizeof(Listnode));

pListnode mynode = (pListnode)malloc(sizeof(Listnode));
mynode->next = NULL;

printf("Please Input the number for the node:");
int  nodecount = 0;
scanf("%d", &nodecount);
int nodenumber = CreateListnode(mynode, nodecount);
printf("nodenumber =====  %d\n", nodenumber);
Traversallist(mynode);

printf("\n after convert the list:\n");
bool ret = ConvertList(mynode);

Traversallist(mynode);

int relnum = releaseListnode(mynode);

free(mynode);
mynode = NULL;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: