-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse_Linked_List.java
More file actions
36 lines (35 loc) · 881 Bytes
/
Reverse_Linked_List.java
File metadata and controls
36 lines (35 loc) · 881 Bytes
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
package com.leet_code;
public class Reverse_Linked_List {
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode root=reverseList(head.next);
head.next.next=head;
head.next=null;
return root;
}
public ListNode reverseList2(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode x=null;
ListNode p=head;
ListNode c=head.next;
while(c!=null){
p.next=x;
x=p;
p=c;
c=c.next;
}
p.next=x;
return p;
}
}