1. 程式人生 > 實用技巧 >idea開啟配置web專案

idea開啟配置web專案

給定一個連結串列,刪除連結串列的倒數第n個節點,並且返回連結串列的頭結點。

示例:

給定一個連結串列: 1->2->3->4->5, 和 n = 2.

當刪除了倒數第二個節點後,連結串列變為 1->2->3->5.
說明:

給定的 n保證是有效的。

進階:

你能嘗試使用一趟掃描實現嗎?

/**
 * @author :xxx
 * @description:TODO
 * @date :2020/10/18 16:29
 */
public class ListNode {
     int val;
     ListNode next;
     ListNode() {}
     ListNode(
int val) { this.val = val; } ListNode(int val, ListNode next){ this.val = val; this.next = next; } } class Solutions { //獲取連結串列的長度 public int getLength(ListNode head) { int len = 0; while (head != null) { len++; head = head.next; }
return len; } public ListNode removeNthFromEnd(ListNode head, int n) { ListNode temp = new ListNode(0, head); ListNode cur = temp; int len = getLength(head); // System.out.println("連結串列的長度為"+len); for (int i = 0; i < len - n ; i++) {//此處n的長度為個坑 cur = cur.next;
// System.out.println("cur的內容:"+cur.val); } cur.next = cur.next.next; return temp.next; } public static void main(String[] args) { ListNode a = new ListNode(1); ListNode b = a; for (int i = 2; i <= 5; i++) { b.next = new ListNode(i); b = b.next; } // ListNode c = a; // while (c != null) { // System.out.println(c.val); // c = c.next; // } Solutions s1 = new Solutions(); ListNode l = s1.removeNthFromEnd(a, 2); while (l!= null) { System.out.println(l.val); l = l.next; } } }