反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
思路:定义3个结点,当前结点cur,前一结点pre,临时结点temp(用于保存cur指向的后继结点);cur指向pre,直到cur遍历到尾结点。
/**
* 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 pre=head;//前一节点
ListNode cur=head.next;//当前节点
ListNode temp=head;
while(cur!=null) {
temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
head.next=null;
return pre;
}
}