Google doesn't help and I haven't been able to find any answers on here either. Can someone help at all?
The following program should output the closest common waypoint from any given two path input, Node* A and Node* B:
class CIS14 {
public:
Node* getClosestCommonWaypoint(Node* A, Node* B);
};
Supposedly each of these waypoints is represented in the C++ class as follows, with each waypoint having just one value (integer) and the pointer pointing to theclass Node {
public:
int value;
Node* next;
Node(int v) : value(v), next(NULL) {}
}; adjacent (next) waypoint:
If two paths share no common path, return NULL
The output should be the same node as the one in the original list; shouldn't dynamically create one - return the same node from the original list
There cannot be multiple common paths in input
Input can be a NULL pointer.
The input paths MUST retain their original structure and values after the function returns
Each path is uni-directional (singly); it won't loop back to any prior node in the same path
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct node
{
int data;
struct node* next;
};
/* Function to get the counts of node in a linked list */
int getCount(struct node* head);
/* function to get the intersection point of two linked
lists head1 and head2 where head1 has d more nodes than
head2 */
int _getIntesectionNode(int d, struct node* head1, struct node* head2);
/* function to get the intersection point of two linked
lists head1 and head2 */
int getIntesectionNode(struct node* head1, struct node* head2)
{
int c1 = getCount(head1);
int c2 = getCount(head2);
int d;
if(c1 > c2)
{
d = c1 - c2;
return _getIntesectionNode(d, head1, head2);
}
else
{
d = c2 - c1;
return _getIntesectionNode(d, head2, head1);
}
}
/* function to get the intersection point of two linked
lists head1 and head2 where head1 has d more nodes than
head2 */
int _getIntesectionNode(int d, struct node* head1, struct node* head2)
{
int i;
struct node* current1 = head1;
struct node* current2 = head2;
for(i = 0; i < d; i++)
{
if(current1 == NULL)
{ return -1; }
current1 = current1->next;
}
while(current1 != NULL && current2 != NULL)
{
if(current1 == current2)
return current1->data;
current1= current1->next;
current2= current2->next;
}
return -1;
}
/* Takes head pointer of the linked list and
returns the count of nodes in the list */
int getCount(struct node* head)
{
struct node* current = head;
int count = 0;
while (current != NULL)
{
count++;
current = current->next;
}
return count;
}
|