/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null ){
return head;
}
ListNode olehead = head;
ListNode myhead = head;
ListNode tmp = head;
while(olehead.next!=null){
tmp = olehead.next;
olehead.next = tmp.next;
tmp.next = myhead;
myhead = tmp;
}
return myhead;
}
}
思路清晰,推荐此方法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
//创建myHead,指向null
//循环开始:head!=null
//储存head的下一个next
//储存myHead的下一个myNext
//myHead指向head,head指向myNext
//head = next
//循环结束。
//返回myHead.next
ListNode myHead = new ListNode(-1);
ListNode next = head;
ListNode myNext = head;
while(head!=null){
next = head.next;
myNext = myHead.next;
myHead.next = head;
head.next = myNext;
head = next;
}
return myHead.next;
}
}