首页 > 代码库 > 【练习】P62

【练习】P62

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


/*-单链表版本-*/
#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;
}