define a class for a linked list and write a method to delete the nth node.
1、问题
define a class for a linked list and write a method to delete the nth node.
2、算法
template <typename C>
struct Node{
C content ;
Node<C>* next ;
}
template <typename T>
class List{
private:
Node<T>* head ;
unsigned int size ;
public:
List()
{
size = 0 ;
head = NULL ;
}
Node<T>* getHead() { return head ; } ;
bool insert(const T& data)
{
Node<T>* node = new Node<T> ;
node->content = data ;
node->next = head;
head = node ;
size++ ;
return true ;
}
bool insert(const T&data, int pos)
{
if( pos > size )
{
return false ;
}else if( pos == 0 )
{
return insert(data) ;
}
Node<T>* node = new Node<T> ;
node->content = data ;
node->next = NULL ;
unsigned int idx = 1 ;
Node<T>* frontNode = head ;
while(idx < pos)
{
idx++ ;
frontNode = frontNode->next ;
}
node->next = frontNode->next ;
frontNode ->next = node ;
size++ ;
return true ;
}
bool remove( int pos )
{
if( pos > size )
{
return false ;
}
unsigned int idx = 0 ;
Node<T>* frontNode = NULL ;
Node<T>* node = head ;
while(idx < pos)
{
idx++ ;
frontNode = node ;
node = node->next ;
}
if( frontNode )
{
frontNode->next = node->next ;
}else{
head = head->next ;
}
delete node ;
size-- ;
return true ;
}
}
相关文章
- Java中List集合去除重复数据的方法
- SAP Fiori Elements List Report table 里的普通按钮,Global 按钮 和 Determining 按钮
- Atitit s2018.5 s5 doc list on com pc.docx v2
- 已解决TypeError:List indices must be integers or slices , not str
- 源码详解数据结构Linked List
- 002-redis-数据类型(string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合))
- [LeetCode] Delete Node in a Linked List
- python使用技巧(三十二):将整个list都是数值的字符串转为正常的数值list--->案例:str = “[1,2,3,5,7,10]“