1006. insert for single link list with head node
2016-10-20 10:43
429 查看
带虚拟头结点的单链表结点结构如下:
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函数。
Problem Source: LXM
我的代码
// Problem#: 19147 // Submission#: 4809302 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ // All Copyright reserved by Informatic Lab of Sun Yat-sen University void List::insert(int toadd, int pos) { ListNode *pre = head; if (pos <= 0) return; while (--pos && pre->next != NULL) { pre = pre->next; } ListNode * add = new ListNode; add->data = toadd; if (pre->next != NULL) { add->next = pre->next; } else { add->next = NULL; } pre->next = add; }
相关文章推荐
- 1007. remove for single link list with head node
- SingleLinkNode with Pointers-to-Pointers
- [c++] list with head node
- demo for insert values into sorted single list
- Single link list
- Another Single Link List
- Repeated column in mapping for entity:(should be mapped with insert="false" update="false")
- linux核list_for_each_entry(pos, head, member)分析
- Repeated column in mapping for entity: .... should be mapped with insert="false" update="false"
- JSLink to custom list to render people column in detail with picture
- The Link List with C
- Repeated column in mapping for entity:should be mapped with insert="false" update="false"
- JSLink to render the list to show people detail info with picture
- Linux内核 hlist_head/hlist_node结构解析
- Parsing web.config with XmlDocument.SelectSingleNode
- list中节点如何与迭代器关联(List中iterator begin() { return (link_type)((*node).next); }的疑问)
- 【11】Delete a node in the middle of a single linked list
- Linux内核 hlist_head/hlist_node结构解析
- Node.js: Building for Scalability with Server-Side JavaScript
- Bug 10636231- High version count for INSERT .. RETURNING statements with reason INST_DRTLD_MISMATCH