Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Hi Dear,
- Question is long.
- I have answered Q1. Please post others in separate post.
- I have tested , its working fine.
- /**
- * Created by pravesh on 12/04/18.
- */
- public class LList<T extends Comparable<T>>
- {
- Node<T> head; // head of list
- /* Linked list Node*/
- class Node<T>
- {
- T data;
- Node<T> next;
- Node(T d) {data = d; next = null; }
- }
- /* Appends a new node at the end. This method is
- defined inside LinkedList class shown above */
- public void append(T new_data)
- {
- /* 1. Allocate the Node &
- 2. Put in the data
- 3. Set next as null */
- Node new_node = new Node(new_data);
- /* 4. If the Linked List is empty, then make the
- new node as head */
- if (head == null)
- {
- head = new Node(new_data);
- return;
- }
- /* 4. This new node is going to be the last node, so
- make next of it as null */
- new_node.next = null;
- /* 5. Else traverse till the last node */
- Node last = head;
- while (last.next != null)
- last = last.next;
- /* 6. Change the next of last node */
- last.next = new_node;
- return;
- }
- public int finds(T item) {
- if(head == null)
- return 0;
- Node<T> temp = head;
- int i = 0;
- while(temp != null) {
- i++;
- if(temp.data.compareTo(item) == 0)
- return i;
- temp = temp.next;
- }
- return 0; // not found
- }
- /* This function prints contents of linked list starting from
- the given node */
- public void printList()
- {
- Node tnode = head;
- while (tnode != null)
- {
- System.out.print(tnode.data+" ");
- tnode = tnode.next;
- }
- }
- /* Driver program to test above functions. Ideally this function
- should be in a separate user class. It is kept here to keep
- code compact */
- public static void main(String[] args)
- {
- /* Start with the empty list */
- LList<Integer> llist = new LList<>();
- llist.append(6);
- llist.append(7);
- llist.append(1);
- llist.append(4);
- llist.append( 8);
- System.out.println("\nCreated Linked list is: ");
- llist.printList();
- System.out.println();
- System.out.println("Searching 9");
- System.out.println(llist.finds(9));
- }
- }
- Output:
- Created Linked list is:
- 6 7 1 4 8
- Searching 9
- 0
- Please DONT forgot to rate my answer. We are working hard for you Guys!!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement