#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
node * InitLink()
{
node *p,*head,*newNode;
head = (node*)malloc(sizeof(node));
p = head;
int array[] = {1,133,313,122,11,12,22,85,52};
int i = 0;
while(i<sizeof(array)/sizeof(int))
{
newNode = (node*)malloc(sizeof(node));
newNode->data = array[i];
p->next = newNode;
p = p->next;
p->next = NULL;
i++;
}
head = head->next;
return head;
}
void print(node *head){
node *p = head;
if(head!=NULL)
{
while(p!=NULL)
{
printf("%d\n",p->data);//122,133,313,122,11,12,22,85,52
p = p->next;
}
}
};
node *deleteNode(node *head,int num)
{
node *p1 ,*p2;
p1 = head;
while(num!=p1->data&&p1->next!=NULL)
{
p2 =p1;
p1 = p1->next;
}
if(num == p1->data)
{
if(p1 == head)
{
head = head->next;
free(p1);
}
else
{
p2->next = p1->next;
free(p1);
}
}
else
printf("%d couldn't be found\n",num);
return head;
}
int main()
{
node *head = InitLink();
head = deleteNode(head,52);
print(head);
return 0;
}
C 单链表删除节点
最新推荐文章于 2023-10-27 11:12:30 发布