这个问题开始我考虑的是把前后的两个奇偶节点内的数据相交换,这岂不是很简单,但是后来一想,不是那么回事,这个题目主要是考察我们对单链表操作的理解。所以引发我个人的一个小观点,就是学习的目的不是为了追求结果,而且要学到方法。我们需要注重的不是问题的结果,而是求解的过程。所以,这个题本着原则来讲,是需要改变指针的指向的。
如果是偶数个节点,那很好办,奇偶对调,如果是奇数个节点,那么最后一个节点肯定不用进行和其他节点的交换,所以这就给出了判断程序结束的条件,就是当cur&&cur->next都为真的时候,程序才进行,当cur为NULL,或者cur->next我NULL的时候,程序结束。下面贴上程序,同时给出个人建议,就是当我们光看程序看不懂的时候,可以画图进行理解。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Node
{
char data;
struct Node *next;
}Node,*LinkList;
void create_list(const char *str,LinkList *head)
{//the head node contain key word
int len=strlen(str);
int i;
Node *temp=NULL;
Node *p=NULL;
for(i=0;i<len;i++)
{
p=(Node*)malloc(sizeof(Node));
p->data=str[i];
p->next=NULL;
if((*head)==NULL)
{
*head=p;
temp=p;
}
else
{
temp->next=p;
temp=p;
}
}
}
void inverse_list(LinkList *head)
{//inverse the link list
Node *pre=NULL;
Node *cur=*head;
Node *next=NULL;
while(cur&&cur->next)
{
if(pre==NULL)
*head=cur->next;
else
pre->next=cur->next;
pre=cur;
next=cur->next->next;
cur->next->next=cur;
cur->next=next;
cur=next;
}
}
void print_list(LinkList head)
{//print link list
Node *temp=head;
while(temp)
{
printf("%c\t",temp->data);
temp=temp->next;
}
printf("\n");
}
void delete_list(LinkList *head)
{//delete link list
if((*head)==NULL)
return;
Node *cur=*head;
Node *next=NULL;
while(cur)
{
next=cur->next;
free(cur);
cur=next;
}
*head=NULL;
}
int main(void)
{
char str[]="abcdefgh";
LinkList head=NULL;
create_list(str,&head);
print_list(head);
inverse_list(&head);
print_list(head);
delete_list(&head);
return 0;
}
gcc -Wall test.c -o test 的结果是:
a b c d ef g h
b a dc f e h g