您的位置:首页 > 其它

单链表反转,单链表创建,单链表尾部插入,单链表打印

2016-08-06 16:35 351 查看
其实,给我感觉,单链表的反转跟链表头部是同一个原理!

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

typedef struct Node{
int num;
struct Node *next;
}List;

int display_list(List *list);
List *create_list();
List insert_list_tail(List *head, int i);
int reverse_single_linked_list(List *list);

int main()
{
int i;
List *head = create_list();
for(i=1; i<6; i++)
insert_list_tail(head, i);
display_list(head);
reverse_single_linked_list(head);
display_list(head);
free(head);
return 0;
}

int display_list(List *list)
{
List *p = list;
if(NULL == p->next){
printf("The list is empty!\n");
return -1;
}
while(NULL != p->next){
printf("%d->", p->next->num);
p = p->next;
}
printf("\n");
return 0;
}

List *create_list()
{
List *list = NULL;
list = malloc(sizeof(List));
if(NULL == list){
printf("malloc memory failed!\n");
exit(-1);
}
// initialize head node
list->num = '\0';
list->next = NULL;

return list;
}

List insert_list_tail(List *head, int i)
{
List *new_node = NULL;
List *p = head;

new_node = malloc(sizeof(List));
if(NULL == new_node){
printf("malloc memory failed!\n");
exit(-1);
}
// 1.initialize new node
new_node->num = i;
new_node->next = NULL;

// 2.put the new node noto list tail
while(NULL != p->next){
p = p->next;
}
p->next = new_node;
}

int reverse_single_linked_list(List *list)
{
if(NULL == list->next || NULL == list->next->next){
printf("Empty list or Only one node!\n");
return -1;
}
List *temp_list = list->next;
List *cur = NULL;
list->next = NULL;
while(NULL != temp_list->next){
cur = temp_list;
temp_list = temp_list->next;
cur->next = list->next;
list->next = cur;
}

// The tail node of temp list
temp_list->next = list->next;
list->next = temp_list;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐