删除链表一个结点时间复杂度为O(1)

版权声明: https://blog.csdn.net/if_i_were_a/article/details/82530246

/*剑指offer p119 面试题18 
在O(1)时间内删除链表结点 */
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
    int data;
    struct node *next;
} LinkNode;
LinkNode * createLinkList()
{
    LinkNode *p,*t,*h;
    int x;
    h=(LinkNode *)malloc(sizeof(LinkNode));
    h->next=NULL;
    t=h;
    printf("请输入要创建的节点的值");
    scanf("%d",&x);
    while(x!=-1)
    {
        p=(LinkNode *)malloc(sizeof(LinkNode));
        p->data=x;
        p->next=NULL;
        t->next=p;
        t=p;
        scanf("%d",&x);
    }
    return h;    
}
void printLinkList(LinkNode *h)
{
    LinkNode *p;
    for(p=h->next;p;p=p->next)
    printf("%d ",p->data);
}
LinkNode* deleteNode(LinkNode *h,LinkNode *p)
{
    LinkNode *q;
    if(p->next==NULL)
    {
        for(q=h;q->next!=p;q=q->next);
        q->next=p->next;
        free(p);
    }
    else
    {
        p->data=p->next->data;
        q=p->next;
        p->next=q->next;
        free(q);
    }
    return h;
}
int main(void)
{
    LinkNode * head,*p;
    head=createLinkList();
    //先给定一个链表的节点
   p=head->next;
//    p=head->next->next->next->next; 
    deleteNode(head,p);
    printLinkList(head);
}

猜你喜欢

转载自blog.csdn.net/if_i_were_a/article/details/82530246