#include<stdio.h> #include<assert.h> #include<stdlib.h> typedef int DataType; typedef struct SListNode { DataType data; struct SListNode* next; }SListNode; SListNode* BuyNode(DataType x) { SListNode* next = (SListNode*)malloc(sizeof(SListNode)); next->data = x; next->next = NULL; return next; } void PushBack(SListNode* & ppHead, DataType x) { if (ppHead == NULL) { ppHead = BuyNode(x); } else { SListNode* tail = ppHead; while (tail->next != NULL) { tail = tail->next; } tail->next = BuyNode(x); } } void PrintSNodeList(SListNode* ppHead) { while (ppHead) { printf("%d->", ppHead->data); ppHead = ppHead->next; } printf("\n"); } //在无头单链表的一个非头节点前插入一个节点 void InsertFront(SListNode* & ppHead, SListNode* pos,DataType x) { assert(ppHead); SListNode* ppHeadName = ppHead; while (ppHeadName != pos) { ppHeadName = ppHeadName->next; } if (ppHeadName == NULL) { return; } SListNode* cur = BuyNode(x); cur->next = pos->next; pos->next = cur; cur->data = x; DataType tmp = cur->data; cur->data = pos->data; pos->data = tmp; } void Test3() { SListNode* List = NULL; PushBack(List, 1); PushBack(List, 2); PushBack(List, 3); PushBack(List, 4); PushBack(List, 5); PrintSNodeList(List); InsertFront(List, List->next->next, 10); PrintSNodeList(List); } int main() { Test3(); system("pause"); return 0; }
原文:http://10740184.blog.51cto.com/10730184/1734403