struct Node { int Data; struct Node* next; }; /** * @brief 该函数实现了在带头结点单链表中第i个结点之前插入元素 * @param[in] head 待插入结点链表 * @param[in] i 待插入结点位置 * @param[in] e 待插入结点值 * @author wlq_729@163.com * http://blog.csdn.net/rabbit729 * @version 1.0 * @date 2009-03-09 */ int ListInsert(Node* head, const int i, const int e) { assert(head); if (head->next == NULL) { return -1; } // 寻找待插入结点的前驱结点,并用prior指向待删除结点的前驱结点 int j = 0; Node* prior = head; while ((prior->next != NULL) && (j < i-1)) { prior = prior->next; j++; } // 插入结点 Node* q = new Node; assert(q); q->Data = e; q->next = prior->next; prior->next = q; return 0; } /** * @brief 该函数实现了在带头结点单链表中与给定值相等的第一个结点前插入结点 * @param[in] head 待插入结点链表 * @param[in] e 待插入结点的位置 * @param[in] data 待插入结点值 * @author wlq_729@163.com * http://blog.csdn.net/rabbit729 * @version 1.0 * @date 2009-03-09 */ int ListInsert1(Node* head, const int e, int data) { assert(head); if (head->next == NULL) { return -1; } Node* q = head->next; Node* prior = head; while ((q != NULL) && (q->Data != e)) { prior = q; q = q->next; } // 插入结点 if((q != NULL) && (q->Data == e) ) { Node* t = new Node; assert(t); t->Data = data; t->next = prior->next; prior->next = t; return 0; } else { cout<<"Could not find data!"<<endl; return -1; } }