翻转链表
Reverse linked list
解题思路
有如下链表:1->2->3->4->5->null
prev | curr | temp |
---|---|---|
null | 1->2->3->4->5->null | 2->3->4->5->null |
1->null | 2->3->4->5->null | 3->4->5->null |
2->1->null | 3->4->5->null | 4->5->null |
3->2->1->null | 4->5->null | 5->null |
4->3->2->1->null | 5->null | null |
5->4->3->2->1->null | null | null |
每次翻转都执行下面的代码:
temp = curr.next;
curr.next=prev;
prev=curr;
curr=temp;
完整代码
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode ReverseList (ListNode head) {
// write code here
if(head == null || head.next == null) {
return head;
}
ListNode prev = null;
ListNode curr = head;
ListNode temp = null;
// 从1开始翻转 temp = curr.next; curr.next=prev; prev=curr; curr=temp;
while(curr != null) {
temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}
}