reverse linked list

Reverse a singly linked list.

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

* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null)
return head;
LinkedList<ListNode> temp=new LinkedList<>();
while(head!=null)
{
temp.add(head);
head=head.next;
}
ListNode tempNode=temp.remove(temp.size()-1);
ListNode resultNode=tempNode;
while(!temp.isEmpty())
{
tempNode.next=temp.remove(temp.size()-1);
tempNode=tempNode.next;
}
tempNode.next=null;
return resultNode;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class  {

* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
if(head==null||head.next==null)
return head;
ListNode cur=head.next;

head.next=null;
while(cur!=null)
{
ListNode temp=cur.next;
cur.next=head;
head=cur;
cur=temp;
}
return head;
}
}