程序员面试宝典之数据结构基础----②单链表删除节点(读后)

来源:互联网 发布:淘宝怎么关闭花呗 编辑:程序博客网 时间:2024/05/17 06:15

删除节点比较简单,但要注意两种情况,是否头结点? ----细节决定成败。

本次删除借助了上篇的创建单链表,代码放在了一块,便于测试。。。。

#include <iostream>#include <stdio.h>#include <stdlib.h>using namespace std;//notice the define of struct, the node is not a variable,it is the name of the struct.so it can be used to define the struct variable.//notice the key word of typedef. if there is not the key word ,the node will have different properties.typedef struct student{    int data;    struct student* next;}node;node* creat(){    node* head,*p,*s;    int x=0,cycle = 1 ;    head=(node*)malloc(sizeof(node));   //notice the malloc is contained in the lib of <stdlib.h> and must malloc the space for the node before you use it.    p = head;    while(cycle)    {        printf("\nPlease input the data:");        scanf("%d",&x);        if(x!= 0)   // only for test ,so the '0' is the symblo of the end but the value of the node,I ignore this kind of possible. Of course you can do it .        {            s = (node*)malloc(sizeof(node));            s->data = x;            printf("\n%d",s->data);            p->next = s;            p = s;        }        else        cycle = 0;    }    head = head->next;    p->next = NULL;    printf("\n  yyy  %d %d %d %d",head->data,head->next->data,head->next->next->data, head->next->next->next->data);//print four node for test.    return(head);}int length(node* head){    int n = 0;    node *p;    p = head;    while(p!=NULL)    {        p = p->next;        n++;    }    return n;}void print(node* head){    node *p;    int n;    n = length(head);    printf("\nNow,These %d records are:",n);    p = head;    if(head!= NULL)    {        while(p != NULL)        {        printf("\n   uuu  %d   ",p->data);        p = p->next;        }    }}//删除head单链表中值为num的节点:node* del_node(node* head ,int num){    //注意分两种情况,删除的是头结点或者非头结点    node* p1, *p2;    p2 = head;    while(num != p2->data && NULL != p2->next)    {        p1 = p2;        p2 = p2->next;    }    if(num == p2->data)    {        if(head == p2)        {            head = p2->next;            free(p2);        }        else        {            p1->next = p2->next;            free(p2);        }    }    else    {        printf("%d could not been found ",num);    }return head;}int main(){    node* head = creat();    print(head);    node* head_new = del_node(head,1);//此处注意,del_node是有返回值的,返回一个新的head,所以,下一个print的时候要给与新的head值。    print(head_new);}

删除的是头结点的打印结果:



Please input the data:1


1
Please input the data:2


2
Please input the data:3


3
Please input the data:4


4
Please input the data:5


5
Please input the data:6


6
Please input the data:7


7
Please input the data:0


  yyy  1 2 3 4
Now,These 7 records are:
   uuu  1
   uuu  2
   uuu  3
   uuu  4
   uuu  5
   uuu  6
   uuu  7
Now,These 6 records are:
   uuu  2
   uuu  3
   uuu  4
   uuu  5
   uuu  6
   uuu  7
Process returned 0 (0x0)   execution time : 5.081 s
Press any key to continue.


原创粉丝点击