Find the nth to last element of a singly linked list
来源:互联网 发布:搜一次CMS 编辑:程序博客网 时间:2024/06/01 19:03
Question:
Implement an algorithm to find the nth to last (倒数第n个) element of a singly linked list.
Analyze:
we can simply use two pointers, and fix one position of the pointer and set it to the head of the list, and then, move another pointer to the place where the distance between these two pointers is n. Then, we move both pointers at the same time until one of the pointer reaches the end of the list.
Code:
public static Node nthtoLastNode(Node head, int n) {Node node = head;int count = n - 1; //be aware!//move the pointer to the place where//the distances between these two pointers is nwhile (count >= 1 && node.next != null) {count--;node = node.next;}//the length of the list is less than nif (count != 0) return null;// move the two pointers together while (node.next != null) {head = head.next;node = node.next;}return head;}http://blog.csdn.net/beiyetengqing
- Find the nth to last element of a singly linked list
- [CrackCode] 2.2 Find the nth to last element of a singly linked list
- 【10】Find nth to last element of a singly linked list
- To find the kth to Last Element of a Singly Linked List
- Q2.2 Find the kth to last element of a singly linked list
- Ch2-2: return the nth to the last node data of a singly linked list
- 1、Find the last element of a list.
- How do you find length of a Singly Linked list
- 1007. Find the middle element in a Linked List
- LinkedList---Delete Node in the Middle of Singly Linked List
- #372 Delete Node in the Middle of Singly Linked List
- Delete Node in the Middle of Singly Linked List
- define a class for a linked list and write a method to delete the nth node.
- Get middle element of a linked-list
- Reverse a singly linked list python
- Convert Sorted List to Binary Search Tree -- leetcodeGiven a singly linked list where elements are s
- LeecCode Reverse Linked List; Reverse a singly linked list.
- LintCode 372: Delete Node in the Middle of Singly Linked List
- Android中的style和theme
- android从Assets文件夹读文本的方法
- mybatis简单应用(基于配置文件)
- 页面头部出现空白,页面头部出现 隐藏字符
- mybatis与spring整合(基于Annotation)
- Find the nth to last element of a singly linked list
- 异常:getOutputStream() has already been called for this response
- MyBatis简介与配置MyBatis+Spring+MySql
- JavaScript 获取当前的日期和时间
- 数据库启动的三个台阶
- Direct3D9的扩展纹理格式
- 六一儿童节倾情奉献,校内首发,CSDN再发,2011年冬季c/c++程序员找工作心得
- 二、十、十六进制转换
- ubuntu 12.04亮度无法保存