单链表之插入删除结点

题:编程实现单链表删除结点。【美国某著名分析软件公司面试题】

解析:如果删除的是头结点,如下图所示。


则把head指针指向头结点的下一个结点,同时free P1结点,如下图所示。


如果删除的是中间结点,如下图所示。


则用P2的next指向P1的next同时,free P1,如下图所示。


答案:完整代码如下:

// P167_example1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <conio.h>

typedef struct student
{
	int data;
	struct student *next;
}node;

//建立单链表
node* create()
{
	node *head,*p,*s;
	int x, cycle = 1;
	head = (node *)malloc(sizeof(node));
	p = head;
	while(cycle)
	{
		std::cout<<"please input the data: ";
		std::cin>>x;
		std::cout<<std::endl;
		if(x != 0)
		{
			s = (node *)malloc(sizeof(node));
			s->data = x;
			p->next = s;
			p = s;
		}
		else
			cycle = 0;
	}
	head = head->next;
	p->next = NULL;
	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);
	std::cout<<"Now, These "<<n<<" records are: "<<std::endl;
	p = head;
	if(p != NULL)
	{
		while(p != NULL)
		{
			std::cout<<p->data<<" -> ";
			p = p->next;
		}
		std::cout<<std::endl;
	}
}
//单链表删除结点
node* del(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 = p1->next;
			free(p1);
		}
		else
		{
			p2->next = p1->next;
			free(p1);
		}
	}
	else
	{
		std::cout<<num<<" could not been found"<<std::endl;
	}
	return head;
}


int _tmain(int argc, _TCHAR* argv[])
{
	node *head;
	head = create();
	print(head);
	//删除结点
	int num;
	std::cin>>num;
	head = del(head, num);
	print(head);	//打印删除后的单链表
	return 0;
}
原文地址:https://www.cnblogs.com/dyllove98/p/3226207.html