1.描述
找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.
2.分析
这道题我的第一反应是用循环链表做,毕竟倒数第几个节点通过循环链表
就转换为了正数第几个节点,但这样也是o(n)的算法,倒不如先通过遍历
找出这个链表到底有多少节点(LEN个节点)进而通过LEN+1-n转换为正数
第几个节点。
3.代码
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: Nth to last node of a singly linked list.
*/
ListNode *nthToLast(ListNode *head, int n) {
// write your code
ListNode *node;
node=head;
int i,LEN=0;
while(node!=NULL)//链表中有多少节点
{
LEN++;
node=node->next;
}
for(i=1;i<LEN+1-n;i++)//倒数第n个节点是正数第LEN+1-n个
{
head=head->next;
}
return head;
}
};
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: Nth to last node of a singly linked list.
*/
ListNode *nthToLast(ListNode *head, int n) {
// write your code
ListNode *node;
node=head;
int i,LEN=0;
while(node!=NULL)//链表中有多少节点
{
LEN++;
node=node->next;
}
for(i=1;i<LEN+1-n;i++)//倒数第n个节点是正数第LEN+1-n个
{
head=head->next;
}
return head;
}
};
4.总结
注意保证链表中节点的最少数量为n,因此外部循环while(node!=NULL)。
内部循环for(i=1;i<LEN+1-n;i++)倒数第n个节点是正数第LEN+1-n个。