題:程式設計實作單連結清單删除結點。【美國某著名分析軟體公司面試題】
解析:如果删除的是頭結點,如下圖所示。
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLi0zaHRGcWdUYuVzVa9GczoVdG1mWfVGc5RHLwkzX39GZhh2csATMflHLwEzX4xSZz91ZsADMx8FdsYkRGZkRG9lcvx2bjxSa2EWNhJTW1AlUxEFeVRUUfRHelRHL2EzXlpXazxyayFWbyVGdhd3LcV2Zh1Wa9M3clN2byBXLzN3btg3PnVGcq5SZlJTZldjNxMTMhRzNjBDZmRWN5YDZ4QDNwYmZzQWZx8CXyAzLchDMxIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjL1M3Lc9CX6MHc0RHaiojIsJye.jpeg)
。
如果删除的是中間結點,如下圖所示。
// 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;
}