题目:
单链表就地逆置
源代码:
#include <stdio.h>
#include <stdlib.h>
struct DATA
{
int num;
};
struct NODE
{
struct DATA data;
struct NODE * next;
};
struct HEAD
{
struct NODE * first;
struct NODE * tail;
};
void initialization(struct HEAD * head);
void create_node(struct HEAD * head,int num);
void node_print(struct HEAD * head);
void inversion_linked(struct HEAD * head);
int main()
{
struct HEAD head;
int num,next;
initialization(&head);
printf("请输入你要插入的数字: ");
while(scanf("%d",&num))
{
create_node(&head,num);
if((next = getchar()) && next != 10 && next != 32) ungetc(next,stdin);
else if(next == 10) break;
}
inversion_linked(&head);
printf("逆序的结果是: ");
node_print(&head);
return 0;
}
void initialization(struct HEAD * head)
{
head->first = (struct NODE *) malloc (sizeof(struct NODE));
head->first->next= NULL;
}
void create_node(struct HEAD * head,int num)
{
struct NODE * tmp_pointer = (struct NODE *) malloc (sizeof(struct NODE));
tmp_pointer->data.num = num;
tmp_pointer->next = NULL;
if(head->first->next == NULL)
{
head->first->next = head->tail = tmp_pointer;
}
else
{
head->tail->next = tmp_pointer;
head->tail = tmp_pointer;
}
}
void node_print(struct HEAD * head)
{
struct NODE * pointer = head->first->next;
while(pointer != NULL)
{
printf("%d ",pointer->data.num);
pointer = pointer->next;
}
}
void inversion_linked(struct HEAD * head)
{
struct NODE * tmp = head->first->next->next;
struct NODE * tmp_tail;
head->tail = head->first->next;
head->tail->next = NULL;
tmp_tail = head->tail;
head->first->next = tmp;
while(head->first->next)
{
tmp = head->first->next->next;
head->first->next->next = head->tail;
head->tail = head->first->next;
head->first->next = tmp;
}
head->first->next = head->tail;
head->tail = tmp_tail;
}
演示效果:
如果朋友你感觉文章的内容对你有帮助,可以点赞,关注文章和专栏以及关注我哈,嘿嘿嘿我会定期更新文章的,谢谢朋友你的支持哈