[CrackCode] 2.2 Find the nth to last element of a singly linked list
来源:互联网 发布:js 获取cookie的值 编辑:程序博客网 时间:2024/06/06 20:00
Implement an algorithm to find the nth to last element of a singly linked list.
==========
Analysis:
Similar problem as "Remove Nth Node From End of List" in LeetCode. Idea is to use two pointers, distance between which is n. So, when the right pointer reached the end of the link list, the left pointer is pointing to the nth to last element.
public class Answer {public static LinkedListNode solution(LinkedListNode head, int n){if(head == null) return null;LinkedListNode left = head;LinkedListNode right = head;for(int i=0; i<n-1; i++){if(right.next!=null) right = right.next;else return null;}while(right.next!=null){left = left.next;right = right.next;}return left;}public static void main(String[] args) {LinkedListNode head = AssortedMethods.randomLinkedList(10, 0, 10);System.out.println(head.printForward());int nth = 11;LinkedListNode n = solution(head, nth);if (n != null) {System.out.println(nth + "th to last node is " + n.data);} else {System.out.println("null");}}}
Note: Please download crackcode library before running the program.
0 0
- [CrackCode] 2.2 Find the nth to last element of a singly linked list
- 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
- [CrackCode] 2.3 Delete a node in the middle of a single linked list
- [CrackCode] 4.4 Creates a linked list of all the nodes at each depth of a given tree
- 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.
- [CrackCode] 2.4 Add two numbers and return the sum as a linked list
- Get middle element of a linked-list
- Reverse a singly linked list python
- poj3301(三分-坐标旋转)
- android音频视频播放器
- mahout0.8 分布式运行20newsgroup(dataguru mahout 第一周作业)
- 第3章 Android的事件处理
- 杭电4333扩展kmp
- [CrackCode] 2.2 Find the nth to last element of a singly linked list
- Android网络程序出现HttpHostConnectException及NetworkOnMainThreadException解决方法
- Integer Inquiry
- linux man中文帮助
- Google Java编程风格指南
- ubuntu server 语言设置为英文
- workqueue原理和分析
- [CrackCode] 2.3 Delete a node in the middle of a single linked list
- 67-序列求和