206.反转链表
题目:
代码:
/**
* 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) {
// 设置一个前节点和一个现节点以及一个tmp
ListNode pre, cur, tmp;
cur = head;
pre = null;
while(cur != null){
tmp = cur.next; // 保存cur原始的下一个节点
cur.next = pre; // 反向
pre = cur; // 让pre指向cur现在的位置
cur = tmp; // 将cur指针指向tmp即原来的cur原始的下一个节点
}
return pre;
}
}