1.题目
找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.
2.思路:
这道题和上一道删除倒数第n个节点一模一样啊~~
注意:返回值的时候只需要返回指针(别人告诉我是因为定义类的时候带了* 号 ——!)
思路是复制过来的:)头指针处第一个指针fast下移n-1次后开始判断链表是否只有n个节点;如果有n个以上节点,第二个节点slow开始与fast平行下移,当fast到达最后时 slow刚好到达倒数第n个的前一个,这时返回倒数第n个的值。
3.代码
/**
* Definition for ListNode.
* public class ListNode {
* 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 here
if(head==NULL)
{return NULL;}
int i;
ListNode *fast=head;
ListNode *slow=head;
ListNode *rear=new ListNode(0);
rear->next=head;
for(i=0;i<n;i++)
{
fast=fast->next;
}
if(fast==NULL)
{
return rear->next;
}
while(fast->next!=NULL)
{ fast=fast->next;
slow=slow->next;
}
return slow->next;
}
};
4.感想
算是巩固了删除倒数第n个节点那道题吧~~~