反转链表,leetcode 206题。
思路:
定义三个pre、current、next三个节点。每次遍历需要做的事:
1.next节点赋值(current.next)
2.反转当前节点指针(current.next = pre)
3.pre节点和current节点步进到下一节点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode current = head;
ListNode next;
while(current != null) {
next = current.next;
current.next = pre;
pre = current;
current = next;
}
return pre;
}
}