`
897371388
  • 浏览: 528650 次
文章分类
社区版块
存档分类
最新评论

C 链表的反转(数据结构与算法)

 
阅读更多

建立一个链表,然后将其中的元素进行反转。

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

struct Node
{
	int data;
	struct Node *next;
};

void display_link(struct Node *head)
{	
	struct Node *p;
	for(p = head; p != NULL; p = p->next) {
		printf("%4d",p->data);
	}
	printf("\n");
}

struct Node * new_link()
{
	struct Node *head = NULL, *p1 = NULL ,*p2 = NULL;
	int data;
	int i = 1;
	printf("enter the data:\n");
	p1 = (struct Node * )malloc(sizeof(struct Node));
	while(1) {
		scanf("%d",&p1->data);
		if(head == NULL) {
			head = p1;
		}
		p2 = p1;
		if(i == 10) {
			break;
		}
		p1 = (struct Node*)malloc(sizeof(struct Node));
		p2->next = p1;
		i++;
	}
	p2->next = NULL;
	
	return head;
}

struct Node *transvert_link(struct Node *head)
{
	struct Node *p,*p2,*p3;
	
	p = head;
	p2 = head->next;
	p3 = head->next->next;
	while(p3 != NULL) {
		p2->next = p;
		p = p2;
		p2 = p3;
		p3 = p3->next;
	}
	p2->next = p;
	head->next = NULL;

	return p2;
}

int main(void)
{
	struct Node *head;
	
	head = new_link();
	printf("\n the data before transvert is:\n");
	display_link(head);
	head = transvert_link(head);
	printf("\n the data after transvert is:\n");
	display_link(head);
	
	return 0;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics