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"