荣誉版主
- 积分
- 34020
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-9-12
- 最后登录
- 1970-1-1
|
Solution1
Idea:
1. iterate the LinkedList first, and calculate the size of the list, mark as n
2. iterate the list again until it reach the n – k element and return
3. move p1 and p2 a end of the linkedList, the p1 will be the Kth node and return the val of p1
Time Complexity: O(n)
Space Complexity: O(1)
Solution2
Idea: using two pointers
1. two pointers p1 and p2, initial set at the head of the input LinkedList
2. just move the p2 to the Kth node of the list
3. move p1 and p2 at the same space
4. when the p2 hit the end of the linkedList, the p1 will be the Kth node and return the val of p1
Time Complexity: O(n)
Space Complexity: O(1)
Code:
http://www.jyuan92.com/post-440 |
|