[면접문제] 단사슬표 반전-귀속과 비귀속

#include <stdio.h>
#include <stdlib.h>
 
typedef struct _Node
{
	 int data;
	 _Node* next;
 }Node, *LinkList;
 

// 
 LinkList Reverse(LinkList &head) 
 {
	 if(head == NULL)
	 {
		 return NULL;
	 }
	Node *pre, *cur, *next;
	pre = head;
	cur = head->next;
	while(cur)
	{
		next = cur->next;
		cur->next = pre;
		pre = cur;
		cur = next;
	}
	head->next = NULL;
	head = pre;
	return head;
}

// 
 // next NULL
 LinkList RReverse(LinkList p, LinkList &head)
 {
	 if( (p==NULL) || (p->next==NULL) )
	 {
		 head = p;
		 return p;
	 }
	 else
	 {
		 LinkList tmp = RReverse(p->next, head);
		 tmp->next = p;
		 return p;
	 }
 }
 

bool CreateList(LinkList &head, const int *data, const int len) 
 {
	 Node *cur = NULL;
	 Node *next = NULL;
	 int i;
	 cur = (LinkList)malloc(sizeof(Node));
	 if(cur == NULL)
	 {
		return false;
	 }
	 cur->data = data[0];
	 cur->next = NULL;
	 head = cur;
	 for(i=1; i<len; i++)
	 { 
		 next = (LinkList)malloc(sizeof(Node));
		 if(next == NULL)
		 {
			 return false;
		 }
		 next->data = data[i];
		 next->next = NULL;
		 cur->next = next;
		 cur = cur->next;
	 }
	 return true;
 }
 
void PrintList(LinkList head) 
 {
	 while(head != NULL)
	 {
		 printf(" %d", head->data);
		 head = head->next;
	 }
 }

void main( void )
 {
	 int data[] = {1, 2, 3, 4, 5, 6};
	 int len = sizeof(data)/sizeof(int);
	 LinkList head;
	 if( !CreateList(head, data, len) )
	 {
		 printf(" !
"); return; } printf(" :"); PrintList(head); printf("
"); Reverse(head); printf(" :"); PrintList(head); printf("
"); LinkList tail = RReverse(head, head); tail->next = NULL; // , printf(" :"); PrintList(head); printf("
"); }

좋은 웹페이지 즐겨찾기