Solution:read
#include <iostream>
using namespace std;
struct node
{
char c;
node *next;
};
node *buildlist(char *);
node *revlist(node *);
void freelist(node *);
/**
******************************************************************************
*
* Reverses a singly linked list
*
* @param argc
* @param argv
*
* @return int
*
******************************************************************************
*/
int main (int argc, char *argv[])
{
char buf[128];
char *str = buf;
cout << "Enter string:";
str = fgets(buf, 127, stdin);
if (str)
{
size_t len = strlen(str) -1; // subtract line feed
str[len] = '\0'; // strip line feed
printf("in (%03d): %s\n", len, str);
node *p = buildlist(str);
node *phead = revlist(p);
printf("out(%03d): ", len);
p = phead;
while (p != NULL)
{
printf("%c", p->c);
p = p->next;
}
printf("\n");
freelist(phead);
}
return(0);
}
/**
******************************************************************************
*
* Builds a singly linked list from the string
*
* @param str
*
* @return node* pointing to the head of list
*
******************************************************************************
*/
node *buildlist(char *str)
{
node *head = NULL;
if (str)
{
node *p = new node;
if (p != NULL)
{
head = p;
p->c = *str++;
p->next = NULL;
node *q;
while (*str != '\0')
{
q = new node;
if (q != NULL)
{
q->c = *str++;
q->next = NULL;
p->next = q;
p = q;
}
else {
printf("Cannot allocate node\n");
break;
}
}
}
else {
printf("Cannot allocate head node\n");
}
}
return head;
}
/**
******************************************************************************
*
* Frees all the nodes in the list
*
* @param p - pointer to head of list
*
******************************************************************************
*/
void freelist(node *p)
{
node *q;
while (p != NULL)
{
q = p->next;
delete p;
p = q;
}
}
/**
******************************************************************************
*
* Reverse the list
*
* @param p - pointer to head of list
*
* @return node* pointing to the head of reversed list
*
******************************************************************************
*/
node *revlist(node *p)
{
node *cur = NULL;
if (p != NULL)
{
node *nxt;
node *old;
// initializes local pointers
cur = old = p;
nxt = p->next;
p->next = NULL; // root becomes tail, sets root->next to null
while (nxt != NULL)
{
cur = nxt; // operates on this node
nxt = cur->next; // advances nxt pointer
cur->next = old; // reverses link - points to previous node
old = cur; // old points to head node of reversed list
}
}
return cur; // points to head of reversed list
}
hide solution
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.