带哨兵节点和不带哨兵节点的单链表操作的对比

```typedef struct _node{
int data;
struct _node *next;
}node, *pNode;```

```pNode createList(void)
{
pNode temp;
pNode prev;
int input;
pNode head = NULL;
scanf("%d", &input);
while(input != -1){
temp = (pNode)malloc(sizeof(node));
temp->data = input;
temp->next = NULL;
//需要考虑链表为空的情况
if(head == NULL){
head = temp;
prev = temp;
}else{
prev->next = temp;      //链
prev = temp;
}
scanf("%d", &input);
}

return head;
}```

```pNode createListWithSentinel(void)
{
pNode temp;
pNode prev;
int input;
pNode head;
head = (pNode)malloc(sizeof(node));
head->next = NULL;
prev = head;
scanf("%d", &input);
while(input != -1){
temp = (pNode)malloc(sizeof(node));
temp->data = input;
temp->next = NULL;
prev->next = temp;      //链
prev = temp;
scanf("%d", &input);
}

return head;
}```

```void printList(const pNode head)
{
pNode temp = head;
while(temp){
printf("%d, ", temp->data);
temp = temp->next;
}
printf("\n");
}```

```void printListWithSentinel(const pNode head)
{
pNode temp = head;
while(temp->next){
printf("%d, ", temp->next->data);
temp = temp->next;
}
printf("\n");
}```

```pNode insertNodeN(pNode head, int pos, int value)
{
int count;
pNode temp;
pNode prev = head;
temp = (pNode)malloc(sizeof(node));
temp->data = value;
if(head == NULL || pos == 0){
temp->next = head;
return temp;
}
for(count = 1; count < pos && prev->next != NULL; count++){
prev = prev->next;
}
temp->next = prev->next;
prev->next = temp;      //链

return head;
}```

```void insertNodeWithSentinelN(const pNode head, int pos, int value)
{
int count;
pNode temp;
pNode prev = head;
temp = (pNode)malloc(sizeof(node));
temp->data = value;
for(count = 0; count < pos && prev->next != NULL; count++){
prev = prev->next;
}
temp->next = prev->next;
prev->next = temp;      //链
}```

```pNode deleteNodeN(pNode head, int pos)
{
int count;
pNode temp;
pNode prev = head;
/*空表的情况*/
if(head == NULL){
return head;
}
/*删除第一个节点，即删除的是头节点的情况*/
if(pos == 0){
temp = head;
head = head->next;
free(temp);
return head;
}
for(count = 1; count < pos && prev->next != NULL; count++){
prev = prev->next;
}
temp = prev->next;
if(temp != NULL){
prev->next = temp->next;    //还没有到表尾
}
free(temp);
return head;
}```

```void deleteNodeWithSentinelN(const pNode head, int pos)
{
int count;
pNode temp;
pNode prev = head;
for(count = 0; count < pos && prev->next != NULL; count++){
prev = prev->next;
}
temp = prev->next;
if(temp != NULL){
prev->next = temp->next;    //还没有到表尾
}
free(temp);
}```

原文作者：瘋耔
原文地址: https://www.cnblogs.com/Ph-one/p/7069814.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。