Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java ลบสมาชิกจาก LinkedList


บทนำ

ในบทความนี้ เราจะเรียนรู้วิธีการลบสมาชิก (Remove elements) จาก LinkedList คลาส java.util.LinkedList ทำงานแบบ doubly-linked list การดำเนินการที่เข้าถึงด้วยดัชนีจะเดินทางผ่านลิสต์จากจุดเริ่มต้นหรือจุดสิ้นสุด ขึ้นอยู่กับจุดใดที่ใกล้กว่าดัชนีที่ระบุ

ตัวอย่างการทำงาน

อินพุทตัวอย่าง:

The list is defined as: [Java, Scala, Python, JavaScript, C++]

เอาต์พุทที่คาดหวัง:

The list after removing all the elements is: [Python, JavaScript, C++]

อัลกอริทึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศลิสต์
ขั้นตอนที่ 3 - กำหนดค่า
ขั้นตอนที่ 4 - ใช้เมธอด remove() ลบสมาชิก
ขั้นตอนที่ 5 - แสดงผลลัพธ์
ขั้นตอนที่ 6 - จบการทำงาน

ตัวอย่างที่ 1: เขียนในฟังก์ชัน main โดยตรง

import java.util.LinkedList;

public class Demo {
    public static void main(String args[]) {
        LinkedList input_list = new LinkedList();
        input_list.add("Java");
        input_list.add("Scala");
        input_list.add("Python");
        input_list.add("JavaScript");
        input_list.add("C++");
        System.out.println("The list is defined as: " + input_list);
        input_list.remove();
        input_list.remove();
        System.out.println("The list after removing all the elements is: " + input_list);
    }
}

เอาต์พุท

The list is defined as: [Java, Scala, Python, JavaScript, C++]
The list after removing all the elements is: [Python, JavaScript, C++]

ตัวอย่างที่ 2: ใช้เมธอดแยก (Object-Oriented Style)

import java.util.LinkedList;

public class Demo {
    static void remove_element(LinkedList input_list) {
        input_list.remove();
        input_list.remove();
        System.out.println("The list after removing all the elements is: " + input_list);
    }
    
    public static void main(String args[]) {
        LinkedList input_list = new LinkedList();
        input_list.add("Java");
        input_list.add("Scala");
        input_list.add("Python");
        input_list.add("JavaScript");
        input_list.add("C++");
        System.out.println("The list is defined as: " + input_list);
        remove_element(input_list);
    }
}

เอาต์พุท

The list is defined as: [Java, Scala, Python, JavaScript, C++]
The list after removing all the elements is: [Python, JavaScript, C++]

เมธอดลบสมาชิกหลักของ LinkedList:

  • remove() - ลบสมาชิกตัวแรก (หัวลิสต์)
  • remove(int index) - ลบสมาชิกที่ตำแหน่ง index
  • remove(Object o) - ลบสมาชิกที่มีค่าเท่ากับ o (ตัวแรกที่เจอ)
  • removeFirst() - ลบสมาชิกตัวแรก
  • removeLast() - ลบสมาชิกตัวสุดท้าย
  • clear() - ลบสมาชิกทั้งหมด