思路:
使用三个指针,pre指向第一个结点,cur指向要逆置的结点,rear指向逆置结点后边的结点,循环条件为逆置结点存在,reverse函数实现逆置。
下面是实现的代码:
在这里#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int value;
struct Node *next;
}node;
void add ( node**Head, int number );
void print ( node *Head );
void fre ( node *Head );
void reverse ( node **Head );
int main()
{
int number;
node *head = NULL;
do {
scanf("%d", &number);
if ( number != -1 ) {
add(&head, number);
}
}while( number != -1 );
print(head);
reverse(&head);
print(head);
fre(head);
return 0;
}
//使用尾插法添加结点
void add ( node**Head, int number )
{
node *p = (node*)malloc(sizeof(node));
node *last = *Head;
p->value = number;
p->next = NULL;
if ( last ) {
while ( last->next ) {
last = last->next;
}
last->next = p;
}
else {
*Head = p; //要改变一个指针就要向函数中传入指针的指针,所以参数用了二级指针
}
}
void print ( node *Head )
{
node *p = Head;
while ( p ) {
printf("%d\n", p->value);
p = p->next;
}
}
void fre ( node *Head )
{
node *p = Head, *q;
while ( p ) {
q = p;
p = p->next;
free(q);
}
}
void reverse ( node **Head )
{
node *pre = *Head, *cur, *rear, *p = *Head;
if ( pre == NULL || pre->next == NULL )
return ;
cur = pre->next;
while ( cur ) {
rear = cur->next;
cur->next = pre;
pre = cur;
cur = rear;
}
p->next = NULL; //实现逆置后让原来的头结点也就是现在的尾结点的next指针指向NULL
*Head = pre;
}