免费做初级会计试题网站有哪些,wordpress single.php 调用文章内容,北京网站建设策划建设,做任务能赚钱的网站有哪些力扣链接
算法思想#xff1a;由于单链表是单向的#xff0c;想要对当前元素进行操作#xff0c;需找到前一个元素。本题利用双指针#xff0c;初始pre指针指向NULL#xff0c;cur指针指向head.再对局部翻转之前#xff0c;先把下一个结点存到temp指针中。当进行完如下代…力扣链接
算法思想由于单链表是单向的想要对当前元素进行操作需找到前一个元素。本题利用双指针初始pre指针指向NULLcur指针指向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;
}
}