力扣链接
算法思想:由于单链表是单向的,想要对当前元素进行操作,需找到前一个元素。本题利用双指针,初始pre指针指向NULL,cur指针指向head.再对局部翻转之前,先把下一个结点存到temp指针中。当进行完如下代码逻辑后,此时cur指针指向NULL,pre指针指向头结点
代码
/*** 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, cur = head;while (cur != null) {ListNode temp = cur.next;cur.next = pre;pre = cur;cur = temp;}return pre; }
}
/*** 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) {if (head == null) return null;ListNode a = head; //a指向第一个结点ListNode b = head.next; //b指向第二个节点while (b != null) {ListNode c = b.next; //保存第三个节点b.next = a; //翻转 b->aa = b; //后移一位 b = c; //后移一位}//最终a指向最后一个节点,变成第一个结点,b指向空,循环结束head.next =null; //第一个结点变成最后一个节点,next指向nullreturn a;
}
}