Documente Academic
Documente Profesional
Documente Cultură
Node head;
static class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
public static LinkedList insert(LinkedList list, int data)
{
Node new_node = new Node(data);
new_node.next = null;
if (list.head == null) {
list.head = new_node;
}
else {
Node last = list.head;
while (last.next != null) {
last = last.next;
}
last.next = new_node;
}
return list;
}
public static void printList(LinkedList list)
{
Node currNode = list.head;
System.out.print("LinkedList: ");
while (currNode != null) {
printList(list);
deleteByKey(list, 1);
printList(list);
deleteByKey(list, 4);
printList(list);
deleteByKey(list, 10);
printList(list);
}
}
OUTPUT
------------------------------------------------------------------
class LinkedList
{
Node head;
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
void printMiddle()
{
Node slow_ptr = head;
Node fast_ptr = head;
if (head != null)
{
while (fast_ptr != null && fast_ptr.next != null)
{
fast_ptr = fast_ptr.next.next;
slow_ptr = slow_ptr.next;
}
System.out.println("The middle element is [" +
slow_ptr.data + "] \n");
}
}
public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+"->");
tnode = tnode.next;
}
System.out.println("NULL");
}
public static void main(String [] args)
{
LinkedList llist = new LinkedList();
for (int i=5; i>0; --i)
{
llist.push(i);
llist.printList();
llist.printMiddle();
}
}
}
OUTPUT
5->NULL
The middle element is [5]
4->5->NULL
The middle element is [5]
3->4->5->NULL
The middle element is [4]
2->3->4->5->NULL
The middle element is [4]
1->2->3->4->5->NULL
The middle element is [3]
----------------------------------------------
Node(int d)
{
this.data = d;
this.next= null;
}
}
Node head;
void addNode(int data)
{
if(head == null)
{
head = new Node(data);
return;
}
void printList(Node n)
{
while(n != null)
{
System.out.print(n.data);
System.out.print(" ");
n = n.next;
}
}
Node paritionLast(Node start, Node end)
{
if(start == end ||
start == null || end == null)
return start;
Node n = list.head;
while(n.next != null)
n= n.next;
list.sort(list.head , n);
OUTPUT
Linked List before sorting
30 3 4 20 5
Linked List after sorting
3 4 5 20 30
--------------------------------------------------------------------