提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、力扣206. 反转链表
- 二、力扣24. 两两交换链表中的节点
前言
递归写法和双指针法实质上都是从前往后翻转指针指向,其实还有另外一种与双指针法不同思路的递归写法:从后往前翻转指针指向。
一、力扣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) {ListNode p = new ListNode();ListNode r = head; p.next = null;while(r != null){ListNode s = r;r = r.next;s.next = p.next;p.next = s;}return p.next;}
}
二、力扣24. 两两交换链表中的节点
/*** 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 swapPairs(ListNode head) {ListNode L = new ListNode(-1,head);if(head == null || head.next == null){return head;}ListNode p1 = L, p2 = p1.next, p3 = p2.next;while(p2 != null && p3 != null){ListNode s1 = p2, s2 = p3;p2 = p3.next;if(p2 != null){p3 = p2.next;}else{p3 = null;}p1.next = s2;s2.next = s1;s1.next = p2;p1 = s1;}return L.next;}
}