方法一:
简单粗暴,还有点小问题。只是改了节点的值,没有真正交换2个节点
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
int len = getLength(head);
ListNode a = head;
ListNode b = null;
int n = 0;
for(int i=1,j=len-1;i<j;i++,j--){
b = getByIndex(head,j);
n = b.val;
b.val = a.val;
a.val = n;
a = a.next;
}
return head;
}
public int getLength(ListNode head)
{
if( head == null ) return 0;
ListNode a = head;
int len = 1 ;
while(a != null){
a = a.next;
len++;
}
return len;
}
public ListNode getByIndex(ListNode head, int x){
if( x <= 0 || head ==null) return null;
ListNode a = head;
int length =1;
while(a != null)
{
if( x == length ){
return a;
}
a = a.next;
length++;
}
return null;
}
}
方法2
看了一些别人的代码后发现了这种方法,觉得确实很好。就实现了一遍。
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null) return null;
ListNode next = null;
ListNode pre = null;
while(head != null)
{
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}