/* a circular linked list is a list in which the link field of the last node is made to
* point to the first node of the list.
* In the case of circular lists, the empty list also should be circular. So to represent
* a circular list that is empty, it is required to use a header node or a head-node whose
* data field contents are irrelevant.(need am empty header node).
*/
#include<stdio.h>
#include<stdlib.h>
typedef struct _list
{
int _element;
struct _list *_next;
}list_t;
list_t *insert(list_t *head, int n);
void printList(list_t *head);
list_t *mergeList(list_t *head1, list_t *head2);
list_t *reverseList(list_t *head);
main(void)
{
int n;
int x;
list_t *head1 = NULL;
list_t *head2 = NULL;
printf("Input number of nodes in first list: ");
scanf("%d", &n);
while(n--)
{
scanf("%d", &x);
head1 = insert(head1, x);
}
printList(head1);
printf("Input number of nodes in second list: ");
scanf("%d", &n);
while(n--)
{
scanf("%d", &x);
head2 = insert(head2, x);
}
printList(head2);
head1 = mergeList(head1, head2);
printf("Merged list: ");
printList(head1);
head1 = reverseList(head1);
printf("Reversed list: ");
printList(head1);
return;
}
/*creat a circular list: insert at the end of list*/
list_t *insert(list_t *head, int n)
{
list_t *temp;
/* if list is empty then insert a new node as the starting node*/
if(head == NULL)
{
head = (list_t*)malloc(sizeof(list_t));
if(head == NULL)
{
printf("error: malloc\n");
exit(0);
}
head->_element = n;
head->_next = head;//make the pointer to itself as it is a circular list
}
else
{
temp = head;
while(temp->_next != head)//condition of end; traverse the list to the end of list
temp = temp->_next;
temp->_next = (list_t *)malloc(sizeof(list_t)); //
if(temp->_next == NULL)
{
printf("error: malloc\n");
exit(0);
}
temp = temp->_next;
temp->_element = n;
temp->_next = head;
}
return head;
}
/*merge two circular lists: put ont list into the end of another list*/
list_t *mergeList(list_t *head1, list_t *head2)
{
list_t *temp = NULL;
temp = head1;
while(temp->_next != head1)
temp = temp->_next;
temp->_next = head2;
temp = head2;
while(temp->_next != head2)
temp = temp->_next;
temp->_next = head1;
return head1;
}
/* reverse circular linked list */
list_t *reverseList(list_t *head)
{
list_t *curr;
list_t *prev;
list_t *temp;
temp = head;
prev = NULL;
curr = head;
while(curr->_next != temp)
{
head = head->_next;
curr->_next = prev;
prev = curr;
curr = head;
}
curr->_next = prev; // make the last one point to the previous
temp->_next = head; //make the first one point to the last one
return head;
}
void printList(list_t *head)
{
list_t *temp = NULL;
temp = head;
printf("The element in the list: ");
if(head != NULL)
{
do {
printf("%d ", temp->_element);
temp = temp->_next;
}while(temp != head);
}
else
printf("empty list\n");
putchar('\n');
}
循环链表
最新推荐文章于 2012-08-08 14:44:06 发布