-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.java
More file actions
74 lines (70 loc) · 1.38 KB
/
Copy pathLinkedList.java
File metadata and controls
74 lines (70 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
public class LinkedList
{
public static ListNode reverse(ListNode head)
{
if(head == null || head.next==null)
return head;
ListNode p1 = null, p2 = head;
while(head!=null)
{
p2 = head.next;
head.next = p1;
p1 = head;
head = p2;
}
return p1;
}
public static ListNode create(int n,String s)
{
if(n==0)
return null;
int[] arr = new int[n];
for(int i = 0;i<n;i++)
arr[i] = (int)(Math.random()*10);
if(s.equals("sorted"))
for(int i = 0;i<n;i++)
for(int j = 0;j<n-i-1;j++)
if(arr[j]>arr[j+1])
{
arr[j] = arr[j]^arr[j+1];
arr[j+1] = arr[j]^arr[j+1];
arr[j] = arr[j]^arr[j+1];
}
ListNode head = new ListNode();
ListNode result = head;
head.val = arr[0];
ListNode newNode;
for(int i = 1;i<n;i++)
{
newNode = new ListNode();
head.next = newNode;
head = head.next;
head.val = arr[i];
}
head.next = null;
return result;
}
public static void display(ListNode head)
{
System.out.println();
if (head==null)
{
System.out.print("NULL");
System.out.println();
return;
}
if(head.next==null)
{
System.out.print(head.val);
System.out.println();
return;
}
while(head.next!=null)
{
System.out.print(head.val+"->");
head = head.next;
}
System.out.print(head.val);
System.out.println();
}
}