一、题目
二、代码
/**
* Definition for singly-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; }
* }
*/
class Solution
{
public ListNode reverseList(ListNode head)
{
if(head == null) return null;
ListNode MyHead= new ListNode(0);
ListNode ProNode = new ListNode(0);
MyHead.next = head;
ProNode = MyHead.next;
int length = 0;
List<Integer> lists = new ArrayList<Integer>();
// lists.add(100);
// lists.add(200);
// lists.add(300);
// lists.add(400);
while(ProNode!=null)
{
lists.add(ProNode.val);
length++;
ProNode=ProNode.next;
}
ProNode= MyHead.next;
while(ProNode!=null)
{
ProNode.val=lists.get(length-1);
length--;
ProNode=ProNode.next;
}
// System.out.println(lists.get(2));
return MyHead.next;
}
}
三、运行结果
四、附录
二刷 --两个节点的操作
回顾1 : 巧妙
/**
* Definition for singly-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; }
* }
*/
class Solution
{
public ListNode reverseList(ListNode head)
{
if(head==null || head.next==null) return head;
ListNode temp_1;
ListNode temp_2;
ListNode temp_3;
temp_1 = head;
temp_2 = head.next;
temp_1.next = null;
//只需要三个节点 实际操作只有两个节点
while(temp_2!=null)
{
// System.out.println(" temp_1 " + temp_1.val);
// System.out.println(" temp_2 " + temp_2.val);
temp_3 = temp_2.next;
temp_2.next = temp_1;
temp_1 = temp_2;
temp_2 = temp_3;
}
// System.out.println(" " );
// while(temp_1!=null)
// {
// System.out.println( temp_1.val);
// temp_1 = temp_1.next;
// }
return temp_1;
}
}