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

【练习】P62页3.2题


/*---给你一个链表L和另一个链表P,它们包含以升序排列的整数。操作PrintLots(L,P)
	将打印L中那些由P所指定位置上的元素。---*/
#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);
}

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