链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g

这个问题开始我考虑的是把前后的两个奇偶节点内的数据相交换,这岂不是很简单,但是后来一想,不是那么回事,这个题目主要是考察我们对单链表操作的理解。所以引发我个人的一个小观点,就是学习的目的不是为了追求结果,而且要学到方法。我们需要注重的不是问题的结果,而是求解的过程。所以,这个题本着原则来讲,是需要改变指针的指向的。

如果是偶数个节点,那很好办,奇偶对调,如果是奇数个节点,那么最后一个节点肯定不用进行和其他节点的交换,所以这就给出了判断程序结束的条件,就是当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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值