problem with link list

The question is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
Given a linked list of the following nodes:

struct Node
{
  		char item;
  		Node *pNext;
};

Define a function that inputs the head pointer to a linked list of Nodes and
 searches the list for two consecutive same characters.  If it finds two 
consecutive same characters, it should return the address of the first Node 
containing the character, otherwise it should return NULL. 

I have tried doing this without recursion but I am getting stack dump.
Can some one help please..
This is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
char LinkList::cooccurence(ListNode*nodeptr) {
	nodeptr=head;
	ListNode *temp;
	temp = new ListNode;
	ListNode *previousnode=NULL;
	previousnode=NULL;
	if(!head)
		return NULL;
	if(head->next==NULL)
		return NULL;
	else {
		while(nodeptr!=NULL){
			previousnode=nodeptr;
			nodeptr=nodeptr->next;
			if(previousnode->value==nodeptr->value)
				temp=previousnode;
		}
	}
	return temp->value;
}
Last edited on
You are asked to search a previously set up list. So you shouldn't be creating nodes.

Basically, you have a match if current->item == current->pNext->item, plus the usual checks for null.

So the check becomes: current && current->pNext && current->item == current->pNext->item.

Also, it should return the address of the first node.

Putting it together, you get:
1
2
3
4
5
6
7
8
9
10
11
12
ListNode* find_dup(ListNode* pNode)
{
    ListNode* pCurrent = pNode;
    while (pCurrent && pCurrent->pNext)
    {
        if (pCurrent->item == pCurrent->pNext->item)
            returm pCurremt;

        pCurrent = pCurrent->pNext;
    }
    return NULL;
}
Last edited on
Topic archived. No new replies allowed.