码迷,mamicode.com
首页 > 其他好文 > 详细

【练习】P62

时间:2014-05-24 19:41:49      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:class   blog   c   code   ext   a   

/*---分别对单链表和双链表,只使用指针来交换两个相邻的元素。---*/


/*-单链表版本-*/
#include <stdio.h>
#include <stdlib.h>

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

Node *findEnd(Node *list){	
	while(list->next) list = list->next;
	return list;
}

void insert(int val, Node *list){
	Node *p = (Node *)malloc(sizeof(Node));
	p->val = val; p->next = NULL;
	Node *end = findEnd(list);
	end->next = p;
}
Node *creatNewList(){
	return (Node *)malloc(sizeof(Node));
}

void deleteList(Node *list){
	Node *p;
	while(list){
		p = list->next;
		free(list);
		list = p;
	}
}

void print(Node *list, int k){
	int i = 0;
	while(i < k){
		list = list->next;
		++i;
		if(list == NULL){
			printf("Out of list length!");
			return;
		}
	}
	printf("%d ", list->val);
}

Node *find(int k, Node *list){
	int i = 0;
	while(i < k){
		list = list->next;
		++i;
		if(list == NULL){
			printf("Out of list length!");
			return NULL;
		}
	}
	return list;
}

void swap(int a, int b, Node *list){
	Node *k = find(a - 1, list);
	Node *p1 = k->next;
	Node *p2 = p1->next;
	k->next = p2;	
	p1->next = p2->next;
	p2->next = p1;
}

int main(){
	Node *L = creatNewList(), *ptr;
	Node *P = creatNewList();
	L->next = NULL;	
	int a;
	while(scanf("%d", &a) == 1)
		insert(a, L);
	
	swap(3, 4, L);
	ptr = L->next;
	while(ptr){
		printf("%d ", ptr->val);
		ptr = ptr->next;
	}
	printf("\n");
	deleteList(L);
	return 0;
}


/*-双链表版本-*/
#include <stdio.h>
#include <stdlib.h>

/*表结点类型*/
struct Node{
	int val;
	Node *pre, *next;
};

/*创建一个表头即空双链表*/
Node *creatList(){
	return (Node *)malloc(sizeof(Node));
}

/*在链表尾端插入元素*/
void insert(int val, Node *list){
	Node *p = list;
	while(p->next) p = p->next;
	p->next = (Node *)malloc(sizeof(Node));
	p->next->val = val;
	p->next->next = NULL;
	p->next->pre = p;
}

/*找到第i个元素的位置*/
Node *find(int i, Node *list){
	while(i--){
		list = list->next;
		if(list == NULL){
			printf("Out of list length!\n");
			return NULL;
		}
	}
	return list;
}
/*交换两个相邻元素,先改中间的指针*/
void swap(int i, int j, Node *list){
	Node *p1 = find(i, list);
	Node *p2 = p1->next;
	p2->pre = p1->pre;
	p1->next = p2->next;
	p1->pre = p2;
	p2->next = p1;
	p2->pre->next = p2;
	p1->next->pre = p1;
}

/*销毁链表*/
void deleteList(Node *list){
	Node *p;
	while(list){
		p = list;
		list = list->next;
		free(p);
	}
}

int main(){
	Node *list = creatList();
	list->next = NULL; list->pre = NULL;
	int a;
	while(scanf("%d", &a) == 1)
		insert(a, list);
	swap(3, 4, list);
	Node *ptr = list->next;
	while(ptr){
		printf("%d ", ptr->val);
		ptr = ptr->next;
	}
	deleteList(list);
	return 0;
}



【练习】P62,布布扣,bubuko.com

【练习】P62

标签:class   blog   c   code   ext   a   

原文地址:http://blog.csdn.net/chang_mu/article/details/26670455

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!