题目要求
Reverse a singly linked list.
实现思路
通过头插法新建一个链表并将其返回
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode node1= null;
ListNode tmp = head;
while(tmp!= null){
if(node1 == null){
ListNode newNode = new ListNode(tmp.val);
node1 = newNode;
node1.next = null;
}else{
ListNode newNode = new ListNode(tmp.val);
newNode.next = node1;
node1 = newNode;
}
tmp = tmp.next;
}
return node1;
}
}