C语言如何删除链表头节点?

如题所述

这种删除方法是头节点存放值的,这样可以清楚的看到是否删除掉了头节点。

用p保存头节点  p=head;

head指向下一个节点,成为新的头节点 head=p->next;

释放原来的头节点  free(p);


#include<iostream>
#include<stdio.h>
#include <stdlib.h
void printList(struct node *head);
struct node* delHead(struct node *head);
struct node{
    int data;
    struct node* next;
};
int main(){
      int i;
    struct node *tail,*head,*p;
    //尾插法插入数据 
    p=(struct node*)malloc(sizeof(struct node));
    p->data=0;
    tail=head=p;
    tail->next=NULL;
    for(i=1;i<10;i++){
        p=(struct node*)malloc(sizeof(struct node));
        tail->next=p;
        p->data=i;
        p->next=NULL;
        tail=p;
    }
    printList(head);
    head=delHead(head);
      printList(head);
      system("pause");
      return 0;
}
//删除头结点 
struct node* delHead(struct node *head){ 
    struct node *p = head;
      head=p->next;
      free(p); 
      return head;
}
//打印链表 
void printList(struct node *head){ 
    struct node *p = head;
    while (p != NULL){  
        printf("%i ", p->data);
        p = p->next;
    }
    printf("\n");
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-03-03
将定义一个新的指针, 赋值给这个指针第二个节点
然后删除头节点 数据段 等,将头节点赋值成 这个新的指针指向的节点就行了
第2个回答  推荐于2017-09-03
struct a
{
...
struct a* next;
}
struct a* head;//指向头结点
则删除头结点过程:
{
//保存指向头结点的指针
struct a* p;
p=head;
//head指向第二个节点
head=head->next
//释放头结点内存
free(p);
}本回答被提问者采纳
第3个回答  2013-03-03
p->a,其中p为指向链表的指针, a为链表表头节点,假如后续链表为:
a->b;
b->c;
c->d;
要删除链表头节点的话,修改p的指向位置即可:
p->a => p->b;来自:求助得到的回答
第3个回答  2013-03-03
表节点a -》头节点b-》首节点c
**表节点没数据

point p=a->nex;

a->next=p=>next;

free(p);