问题·描述
程序代码的鲁棒性: 有时也称为健壮性,所谓的鲁棒性是指程序能够判断输入是否合乎规范要求,并对不符合要求的输入予以合理的处理
容错性: 同样也是鲁棒性的重要体现。
链表需要注意的几个问题(边界条件)
(1)输入的链表头节点,NULL
(2)输入的链表可能只有一个节点
(3)链表中有环
一文解决所有链表相关问题
- 关于链表节点的翻转
请看如下代码:
ListNode* reverseList(ListNode* head)
{
ListNode* new_list=NULL; // the new_list is new ListNode;
ListNode* option;
ListNode* connect;
while(connect)
{
connect=option->next;
option->next=m;
m=option;
option=connect;
}
return m;
}
注意节点逆序的方法
下面给出剑指offer,相关问题解析
链表的定义:
/*
struct ListNode {
int val;
struct ListNode next;
ListNode(int x) :
val(x), next(NULL) {
}
};/
面试题22·描述 链表第k个节点
输入一个链表,输出该链表中倒数第k个结点。
思路:
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if (pListHead == NULL || k == 0) return NULL;
ListNode* pList_ahead = pListHead;
ListNode* pList_behind = pListHead;
for (int i = 1; i < k ; ++i)
{
if (pList_ahead->next != NULL)
pList_ahead = pList_ahead->next;
else
return NULL;
}
while (pList_ahead->next != NULL)
{
pList_behind = pList_behind->next;
pList_ahead = pList_ahead->next;
}
return pList_behind;
}
};
面试题23·描述 反转链表
输入一个链表,反转链表后,输出新链表的表头。
(1)递归解法
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL||pHead->next==NULL) return pHead;
ListNode* pReverseNode=ReverseList(pHead->next);
pHead->next->next=pHead;
pHead->next=NULL;
return pReverseNode;
}
};
(2)非递归解法
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL) return NULL;//程序鲁棒性
ListNode* pNode=pHead;
ListNode* pReverseHead=NULL;
ListNode* pPrev=NULL;
while(pNode!=NULL){
ListNode* pNext=pNode->next;
if(pNext==NULL)
pReverseHead=pNode;
pNode->next=pPrev;//指针反转
pPrev=pNode;
pNode=pNext;
}
return pReverseHead;
}
};
面试题24·描述 合并链表
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
(1) 递归解法
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1 == NULL) return pHead2;
if (pHead2 == NULL) return pHead1;
ListNode* pMergeList = NULL;
if (pHead1->val <= pHead2->val)
{
pMergeList = pHead1;
pMergeList = pHead1->next = Merge(pHead1->next, pHead2);
}
else if (pHead1->val > pHead2->val) {
pMergeList = pHead2;
pMergeList = pHead2->next = Merge(pHead1, pHead2->next);
}
return pMergeList;
}
};
(2)非递归解法
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode* result = NULL;
ListNode* current = NULL;
if(pHead1 == NULL)
return pHead2;
if(pHead2 == NULL)
return pHead1;
while(pHead1 != NULL && pHead2 != NULL){
if(pHead1->val <= pHead2->val){
if(result == NULL){
current = result = pHead1;
} else {
current->next = pHead1;
current = current->next;
}
pHead1 = pHead1->next;
} else {
if(result == NULL){
current = result = pHead2;
} else {
current->next = pHead2;
current = current->next;
}
pHead2 = pHead2->next;
}
}
if(pHead1 == NULL){
current->next = pHead2;
}
if(pHead2 == NULL){
current->next = pHead1;
}
return result;
}
};