偶然在网上搜索了一下这个程序,发现还不是很好找到容易看的答案,自己写了一个贴上了,已测试。
typedef struct node_s{
int data;
struct node_s *next;
}node_t;
node_t * list_create(int array[],int n)
{
node_t * head = NULL;
node_t * p = NULL;
node_t *pre;
int i;
printf("%s %d n=%d/n",__FUNCTION__,__LINE__,n);
if(n==0)
return NULL;
head = (node_t *)malloc(sizeof(node_t));
head->data = array[0];
head->next = NULL;
pre = head;
for(i=1;i<n;i++)
{
p = (node_t *)malloc(sizeof(node_t));
p->data=array[i];
p->next = NULL;
pre->next = p;
pre =p;
}
return head;
}
/*创建链表*/
node_t * list_q_create(int array[],int n)
{
int i;
node_t *head=NULL,*p=NULL,*tail=NULL;
for(i=0;i<n;i++)
{
p = (node_t *)malloc(sizeof(node_t));
p->data=array[i];
p->next = NULL;
if(head==NULL)
{
head = p;
tail = p;
}
else
{
tail->next=p;
tail = p;
}
}
return head;
}
void output(node_t *head)
{
while(head != NULL)
{
printf("%5d",head->data);
head= head->next;
}
printf("/r/n");
}
/*单链表逆序,实现方法:遍历一遍链表,并将每一个节点的next指针指向其前一个节点*/
node_t *converse(node_t *head)
{
node_t *pnode=NULL;/*用于遍历链表中的节点*/
node_t *pre=NULL; /*用于记录当前节点的上一个节点*/
node_t *pnext=NULL;/*用于保存当前节点的next指针*/
pnode = head;
pre=NULL;
while(pnode != NULL)
{
pnext = pnode->next;
pnode->next = pre;
pre= pnode;
pnode = pnext;
}
return pre;/*遍历到最后pnode必然为NULL,pre指向最后一个节点,因此将其返回*/
}
int intdata[5]={1,22,44,11,67};
void main(void)
{
node_t *head;
node_t *list;
//head = list_create(intdata,5);
head = list_q_create(intdata,5);
output(head);
list = converse(head);
output(list);
}