【LeetCode】Remove Nth Node From End of List && 【九度】題目1517:連結串列中倒數第k個結點
阿新 • • 發佈:2019-01-27
Total Accepted: 8400 Total Submissions: 28316
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
宣告一個新的ListNode指向head,到倒數第n+1個點的時候,將nextset為next.next。注意n和連結串列長度相等以及n為0的情況。
Java AC
時間限制:1 秒記憶體限制:128 兆特殊判題:否提交:557解決:286/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if (n == 0) { return head; } ListNode point = head; int allLen = 0; while (point != null) { point = point.next; allLen++; } if (allLen == n) { return head.next; } int num = 0; point = head; while (point != null && num != allLen - n - 1) { point = point.next; num++; } if (point.next != null) { ListNode tempNode = point.next.next; point.next = tempNode; } return head; } }
題目描述:
輸入一個連結串列,輸出該連結串列中倒數第k個結點。
(hint: 請務必使用連結串列。)
輸入:
輸入可能包含多個測試樣例,輸入以EOF結束。
對於每個測試案例,輸入的第一行為兩個整數n和k(0<=n<=1000, 0<=k<=1000):n代表將要輸入的連結串列元素的個數,k代表要查詢倒數第幾個的元素。
輸入的第二行包括n個數t(1<=t<=1000000):代表連結串列中的元素。
輸出:
對應每個測試案例,
若有結果,輸出相應的查詢結果。否則,輸出NULL。
樣例輸入:
5 2
1 2 3 4 5
1 0
5
樣例輸出:
4
NULL
這個題和remove那個差不多,不過這個要簡單點。但是得建立連結串列。其實如果不要求的話,陣列完全可以實現麼。
Java AC
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class Main {
/*
* 1517
*/
public static void main(String[] args) throws Exception {
StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
while (st.nextToken() != StreamTokenizer.TT_EOF) {
int n = (int) st.nval;
st.nextToken();
int k = (int) st.nval;
LinkedNode node = null;
LinkedNode point = null;
for (int i = 0; i < n; i++) {
st.nextToken();
LinkedNode tempNode = new LinkedNode((int) st.nval ,null);
if (point == null) {
node = tempNode;
point = tempNode;
}else {
point.setNext(tempNode);
point = point.getNext();
}
}
int i = 0;
while (node != null && i != n - k) {
node = node.next;
i++;
}
if (node == null) {
System.out.println("NULL");
}else {
System.out.println(node.getData());
}
}
}
static class LinkedNode{
private int data;
private LinkedNode next;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public LinkedNode getNext() {
return next;
}
public void setNext(LinkedNode next) {
this.next = next;
}
public LinkedNode(int data, LinkedNode next) {
super();
this.data = data;
this.next = next;
}
public LinkedNode() {
super();
}
}
}
/**************************************************************
Problem: 1517
User: wzqwsrf
Language: Java
Result: Accepted
Time:1120 ms
Memory:28588 kb
****************************************************************/