您的位置:首页 > 理论基础 > 数据结构算法

数据结构——算法之(023)( 单链表就地逆置,头插法)

2014-06-04 15:38 295 查看
【申明:本文仅限于自我归纳总结和相互交流,有纰漏还望各位指出。 联系邮箱:Mr_chenping@163.com】

题目:
单向链表的就地逆置

题目分析:

一、方法很多,这里使用头插法

(1)顺序遍历链表,并把每个节点从新插入在头结点后面

(2)其实就是简单的头插法建立链表的过程

算法实现:
#include <stdio.h>
#include <stdlib.h>

typedef struct _list_node
{
int        key;
struct _list_node  *next;
}list_node;

void *list_insert(list_node *head, int key)
{
list_node *p = head;
while(p->next != NULL)
p = p->next;
list_node *node = calloc(1, sizeof(list_node));
node->key = key;
node->next = NULL;

p->next = node;
}

void list_display(list_node *head)
{
list_node *p = head->next;
printf("list:");
while(p != NULL)
{
printf(" %d", p->key);
p = p->next;
}
printf("\n");
}

/*
** 头插法
*/
list_node *list_reverse(list_node *head)
{
list_node *p = head->next;
list_node *q = NULL;
head->next = NULL;
while(p != NULL)
{
q = p->next;          /*保存下一个节点*/
p->next = head->next; /*把节点插入到头结点后面*/
head->next = p;       /*头结点一直指向最新插入的节点*/
p = q;                /*调整指针,指向下一个节点*/
}
}

int main(int argc, char *argv[])
{
list_node *head = calloc(1, sizeof(list_node));
head->key = 0;
head->next = NULL;

list_insert(head, 1);
list_insert(head, 2);
list_insert(head, 3);
list_insert(head, 4);
list_insert(head, 5);

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