How to Append a Node at the head of LinkedList?
public class MyLinkedList {
public static void main(String[] args) {
Node a = new Node(1);
Node b = new Node(2);
Node c = new Node(3);
a.next=b;
b.next=c;
a.printList();
System.out.println("After adding new node");
Node newNode = appendANodeAtHead(a,4);
newNode.printList();
}
private static Node appendANodeAtHead(Node head, int data){
Node newNode = new Node(data);
newNode.next= head;
return newNode;
}
static class Node{
Node next;
int data;
Node(int d){
this.data=d;
}
public void printList(){
Node current=this;
while(current!=null){
System.out.println(current.data+"->");
current = current.next;
}
System.out.println();
}
}
How to Append a Node at the tail of LinkedList?
private static Node appendANodeAtTail(Node head, int data){
Node current = head;
while(head.next !=null){
head = head.next;
}
head.next=new Node(data);;
return current;
}
How to reverse a LinkedList?
private static Node reverse(Node head){
Node reverseList = head;
Node list_todo = head.next;
reverseList.next=null;
while(list_todo !=null){
Node temp = list_todo;
list_todo= list_todo.next;
temp.next=reverseList;
reverseList=temp;
}
return reverseList;
}
How to delete a Node from a LinkedList?
private static Node deleteANode(Node head){
Node current = head;
if(current == null) return null;
if(current == head){
return current.next;
}
return current;
}
How to find out if a linked list is circular or not?
private static boolean circularLinkList(Node head){
Node slow=head;
Node fast=head.next;
while(true){
if(fast == slow || fast.next==slow){
System.out.println("its circular");
return true;
}else{
fast = fast.next.next;
slow = slow.next;
}
if(fast == null || fast.next==null){
System.out.println("its not circular");
return false;
}
}
}
How to remove duplicate nodes from a LinkedList?
private static Node removeDupNodes(Node head){
Node current = head;
Set mySet = new HashSet();
mySet.add(current.data);
while(current.next!=null){
if(!mySet.contains(current.next.data)){
mySet.add(current.next.data);
current = current.next;
}else{
current.next = current.next.next;
}
}
return head;
}
Adding 2 nodes
private static Node addTwoNodes(Node n1, Node n2, int carry){
if(n1 == null || n2 == null || carry == 0) return null;
Node result = new Node(carry);
int value = carry;
if(n1 != null){
value +=n1.data;
}
if(n2 !=null){
value +=n2.data;
}
result.data=value%10;
if(n1 != null || n2 != null || value > 10){
Node more = addTwoNodes(n1 == null ? null : n1.next, n2 == null ? null : n2.next, value >=10 ? 1: 0);
result.next=more;
}
return result;
}
