-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseLinkedList2.java
82 lines (80 loc) · 1.8 KB
/
ReverseLinkedList2.java
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
75
76
77
78
79
80
81
82
public class ReverseLinkedList2 {
public ListNode reverseBetween(ListNode head, int m, int n) {
int diff = n-m;
if(diff==0)
return head;
ListNode beforeRev = head;
ListNode temp = head;
if(m>1)
{
int count = 1;
while(count<m)
{
beforeRev = temp;
temp = temp.next;
count++;
}
}
ListNode befTemp;
/*if(m==1)
{
befTemp = null;
}
else
{
befTemp = beforeRev;
}*/
befTemp = null;
ListNode aftTemp = temp.next;
while(diff>=0)
{
temp.next=befTemp;
befTemp = temp;
temp=aftTemp;
if(aftTemp==null)
{
break;
}
aftTemp = aftTemp.next;
diff--;
}
if(diff>0)
{
aftTemp.next = temp;
temp.next = null;
befTemp.next = aftTemp;
}
if(m==1)
{
head=befTemp;
while(befTemp.next!=null)
befTemp = befTemp.next;
befTemp.next = temp;
return head;
}
else
{
beforeRev.next = befTemp;
ListNode x = befTemp;
while(x.next!=null)
x= x.next;
x.next = temp;
return head;
}
}
public static void main(String[] args) {
ReverseLinkedList2 r = new ReverseLinkedList2();
ListNode a1 = new ListNode(1);
ListNode a2 = new ListNode(2);
ListNode a3 = new ListNode(3);
a1.next = a2;
a2.next = a3;
a3.next=null;
ListNode result = r.reverseBetween(a1, 1, 3);
while(result!=null)
{
System.out.println(result.val + " ");
result=result.next;
}
}
}