Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
- 思路:
一个node指向前一个(需要用temp存储.next本来该指向的node),然后向后移动,pre=cur,cur=temp - 算法:
/**
* 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 null;
}
ListNode cur=head;
ListNode pre=null;
while(cur!=null){
ListNode temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
return pre;
}
}
- 核心代码
ListNode temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
- 启示:
(1)while循环:当非空的时候,就执行代码=把所有有效点都处理一遍
(2)return pre 返回head指向的新的节点