adsense


Thursday, 29 October 2015

JAVA EXAMPLES ADDING ELEMENT TO LINKED LIST PAGE 139

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



JAVA EXAMPLES ADDING ELEMENT TO LINKED LIST







Java Examples - Adding Element to Linked List


Problem Description:
How to add an element at first and last position of a linked list?
Solution:
Following example shows how to add an element at the first and last position of a linked list by using addFirst() and addLast() method of Linked List class.
import java.util.LinkedList;

public class Main {
   public static void main(String[] args) {
      LinkedList lList = new LinkedList();
      lList.add("1");
      lList.add("2");
      lList.add("3");
      lList.add("4");
      lList.add("5");
      System.out.println(lList);
      lList.addFirst("0");
      System.out.println(lList);
      lList.addLast("6");
      System.out.println(lList);
   }
}
Result:
The above code sample will produce the following result.
1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5, 6


No comments: