Description
带虚拟头结点的单链表结点结构如下:
struct ListNode
{
int data;
ListNode *next;
};
链表类接口如下:
class List
{
public:
List()
{
head = new ListNode;
head->next = NULL;
}
~List()
{
ListNode* curNode;
while( head->next )
{
curNode = head->next;
head->next = curNode->next;
delete curNode;
}
delete head;
}
//在链表第pos(pos>0)个结点之前插入新结点,新结点的值为toadd
//链表实际结点从1开始计数。
//调用时需保证pos小等于链表实际结点数
void List::insert(int toadd, int pos);
// Data field
ListNode *head; //head指向虚拟头结点,head-next指向第一个实际结点
};
请实现如下函数:
void List::insert(int toadd, int pos)
只提交insert函数实现,不需要提交类定义及main函数。
参考答案
ListNode *getNode(ListNode *head,int pos){
ListNode*p = head ;
for(int i = 0 ; i < pos; ++i ){
p =p ->next ;
}
return p ;
}
void List::insert(int toadd, int pos){
ListNode* newnode = new ListNode;
newnode->data = toadd;
ListNode* prev_node = getNode(head,pos-1);
ListNode* next_node = prev_node->next;
prev_node->next = newnode;
newnode->next = next_node;
}