提示:文章寫完后,目錄可以自動生成,如何生成可參考右邊的幫助文檔
文章目錄
- 前言
- 一、力扣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;}
}