单链表反转
实现代码
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node* list_init(int length)
{
int i = 0;
struct node *p, *q;
if(length <= 0) {
return NULL;
}else{
p = malloc(sizeof(struct node));
p->data = 0;
}
for(i=1, q=p; i<length; i++) {
q->next = malloc(sizeof(struct node));
q = q->next;
q->data = i;
}
q->next = NULL;
return p;
}
int list_print(struct node *pnode)
{
int i;
for(i=0; pnode; i++) {
printf("node[%i]: %i\n", i, pnode->data);
pnode = pnode->next;
}
return 0;
}
struct node* list_reverse(struct node *pnode)
{
struct node *p, *q = NULL;
while( pnode ) {
p = pnode->next;
pnode->next = q;
q = pnode;
pnode = p;
}
return q;
}
int list_free(struct node *pnode)
{
struct node *p, *q;
p = pnode;
while(p) {
q = p->next;
free(p);
p = q;
}
return 0;
}
int main(int argc, char* argv[])
{
int len;
struct node *pnode = NULL;
printf("input number:");
scanf("%i", &len);
pnode = list_init(len);
list_print(pnode);
list_print(list_reverse(pnode));
list_free(pnode);
}
尚未实现
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。