所谓的鲁棒性是指程序能够判断输入是否合乎规范要求,并对不合要求的输入予以合理的处理。
容错性是鲁棒性的一个重要体现。
提高代码的鲁棒性的有效途径是进行防御性编程。防御性编程是指预见什么地方可能出现问题,并为这些可能出现的问题制定处理方式。
面试题15:链表中倒数第k个结点
方法一:
遍历链表两次。第一次统计出链表中结点的个数,第二次从头结点往后走n-k+1步。
方法二:
一次遍历,使用两个指针。第一个指针从头开始走k-1步,第二个指针保持在链表头部,两个指针的距离保持为k-1,从第k步开始,两个指针一起向后移动,当第一个指针到达链表尾结点时,第二个指针恰好在倒数第k个结点上。
需要注意的地方:
可能出现输入为空指针或者链表结点总数少于k,以及k<=0的情况。
//题目描述
//
//输入一个链表,输出该链表中倒数第k个结点。
#include<windows.h>
#include<iostream>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(k==0)return NULL;
ListNode* p1=pListHead;
int i=0;
for(i=1;i<k&&p1!=NULL;i++){
p1=p1->next;
}
if(p1==NULL)return NULL;
ListNode* p2=pListHead;
while(p1->next!=NULL){
p1=p1->next;
p2=p2->next;
}
return p2;
}
};
int main(){
ListNode* pHead=&ListNode(1);
ListNode*p=pHead;
p->next=&ListNode(2);
p=p->next;
p->next=&ListNode(3);
p=p->next;
p->next=&ListNode(4);
p=p->next;
p->next=&ListNode(5);
p=p->next;
Solution test=Solution();
pHead=test.FindKthToTail(pHead,3);
while(pHead!=NULL){
cout<<pHead->val<<" ";
pHead=pHead->next;
}
system("pause");
return 1;
}
变形题目
//求链表的中间结点。
//如果链表中结点总数为奇数,返回中间结点;如果结点总数是偶数,返回中间结点的任意一个。
#include<windows.h>
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* getMidNode(ListNode *head) {
if(head==NULL)return false;
ListNode*p=head;
ListNode* q=head->next;
if(q==NULL)return false;
while(q!=NULL){
p=p->next;
q=q->next;
if(q==NULL)break;
q=q->next;
}
return p;
}
};
因为快的指针会在环内打转?
对应leetcode上的题目
141. Linked List Cycle https://leetcode.com/problems/linked-list-cycle
//判断一个单向链表是否形成了环形结构。
#include<windows.h>
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL)return false;
ListNode*p=head;
ListNode* q=head->next;
if(q==NULL)return false;
while(q!=NULL){
if(p->val==q->val)return true;
p=p->next;
q=q->next;
if(q==NULL)break;
q=q->next;
}
return false;
}
};
int main(){
ListNode* pHead=&ListNode(1);
ListNode*p=pHead;
p->next=&ListNode(2);
p=p->next;
p->next=&ListNode(3);
p=p->next;
p->next=&ListNode(4);
p=p->next;
p->next=&ListNode(5);
p=p->next;
Solution test=Solution();
cout<<test.hasCycle(pHead);
system("pause");
return 1;
}