Deletes a specified node from a single-chain table.

Source: Internet
Author: User

View plaincopy to clipboardprint? # Include "stdafx. h"
# Include <string>
# Include <iostream>
# Include <cassert>
Using namespace std;
 
Struct Node
{
Int pos;
Node * pNext;
Node (int position =-1, Node * next = NULL)
: Pos (position), pNext (next ){}
};
// Create a single-chain table
Node * CreateSingleList (int arr [], int n)
{
Node * head = new Node;
Node * createNode = NULL;
Node * temp = head;
For (int I = 0; I <n; ++ I)
{
CreateNode = new Node (arr [I]);
Temp-> pNext = createNode;
Temp = createNode;
}
Return head;
}
// Output single-chain table
Void Print (Node * head)
{
While (head-> pNext! = NULL)
{
Cout Head = head-> pNext;
}
Cout <endl;
}
 
// Find the node whose element value is target
Node * FindNode (Node * head, int target)
{
Node * res = NULL;
While (head-> pNext! = NULL)
{
If (head-> pNext-> pos = target)
{
Return head-> pNext;
}
Head = head-> pNext;
}
Return res;
}
// Delete the node with the specified Element value as target
Void RemoveNode (Node * & head, int target)
{
// Find the source node of the target node
Node * curr = head-> pNext;
Node * pre = head;
While (curr! = NULL)
{
If (curr-> pos = target)
{
Break;
}
Else
{
Pre = curr;
Curr = curr-> pNext;
}
}
 
// Delete a node
Pre-> pNext = curr-> pNext;
Curr-> pNext = NULL;
}
Int main ()
{
Const int N = 10;
Int arr [N];
 
For (int I = 0; I <N; ++ I)
{
Arr [I] = I + 1;
}
 
Node * head = CreateSingleList (arr, N );
 
Node * res = FindNode (head, 5 );
Cout <"Find node:" <res-> pos <endl;
 
Cout <"single-chain table :";
Print (head );
Cout <endl;
 
RemoveNode (head, 1 );
Cout <"after deletion :";
Print (head );
Cout <endl;
}

Author: "wangyangkobe's column"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.