链表的插入与删除
题目描述
输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。
链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
详细描述:
本题为考察链表的插入和删除知识。
链表的值不能重复
构造过程,例如
1 <- 2
3 <- 2
5 <- 1
4 <- 5
7 <- 2
最后的链表的顺序为 2 7 3 1 5 4
删除 结点 2
则结果为 7 3 1 5 4
#include <iostream>
using namespace std;
typedef struct ListNode
{
int m_nKey;
struct ListNode* m_pNext;
}ListNode;
//创建链表头结点
ListNode* creatList(int headNumber)
{
//ListNode* pHead = new ListNode[number];
ListNode* pHead = new ListNode;
pHead->m_nKey = headNumber;
pHead->m_pNext = NULL;
return pHead;
}
//插入元素
void insertList(ListNode* head, int data, int position)
{
ListNode* pCurrent = head;
while (pCurrent->m_nKey != position)
{
pCurrent = pCurrent->m_pNext;
}
ListNode* pTemp = new ListNode;
pTemp->m_nKey = data;
pTemp->m_pNext = pCurrent->m_pNext;
pCurrent->m_pNext = pTemp;
}
//删除元素//若删除后链表为空则返回空指针
ListNode* deleteList(ListNode* head, int data)
{
if (head->m_nKey == data && head->m_pNext == NULL)
{
return NULL;
}
if (head->m_nKey == data)
{
ListNode* pHead = head->m_pNext;
return pHead;
}
ListNode* pPre = head;
ListNode* pCurrent = pPre->m_pNext;
while (pPre->m_pNext != NULL)
{
if (pCurrent->m_nKey == data)
{
pPre->m_pNext = pCurrent->m_pNext;
}
pPre = pPre->m_pNext;
pCurrent = pCurrent->m_pNext;
}
return head;
}
//打印链表
void printList(ListNode* head)
{
ListNode* pTemp = head;
while (pTemp->m_pNext != NULL)
{
cout << pTemp->m_nKey << " ";
pTemp = pTemp->m_pNext;
}
cout << pTemp->m_nKey << " ";
}
int main()
{
int num; //链表节点数
while (cin >> num)
{
int headNumber = 0;
cin >> headNumber;
ListNode* pHead = creatList(headNumber);
for (int i = 0; i < num - 1; i++)
{
int data, position;
cin >> data >> position;
insertList(pHead, data, position);
}
//printList(pHead);
//cout << endl;
int deldata;
cin >> deldata;
ListNode* pHead2 = deleteList(pHead, deldata);
printList(pHead2);
cout << endl;
}
return 0;
}
var code = “61c8195c-957d-4eff-b896-4abce1b4ad9e”