反转链表

73 阅读1分钟

1. 反转链表:

image.png

示例: {1,2,3} -> {3,2,1} {} -> {} **代码实现: **

public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public ListNode ReverseList(ListNode head) { // 1 2 3 4
        // 双指针
        ListNode pre = null;
        ListNode next = null;
        // 遍历反转
        while(head != null){
            next = head.next; // next -> 2 3 4 null
            head.next = pre; // head -> 1 null
            pre = head; // pre -> 1 null
            head = next; // head -> 2 3 4 null
        }
        // 遍历1次结束后:
        // head -> 2 3 4 null
        // pre -> 1 null
        // next -> 2 3 4 null 
        return pre;
    }
}

2. 链表内指定区间反转

image.png

`public` `ListNode reverseBetween (ListNode head, ``int` `m, ``int` `n) {`

`        ``// 1 2 3 4 5 6 m=2 n=6`
`        ``//虚拟头节点`
`        ``ListNode dummy = ``new` `ListNode(-``1``);`
`        ``dummy.next = head;`
`        ``//当前指针和前指针`
`        ``ListNode pre = dummy;`
`        ``ListNode current = head;`
`        ``//找出m位置`
`        ``for` `(``int` `i = ``1``; i < m; i++) {`
`            ``pre = current;`
`            ``current = current.next;`
`        ``}`

`        ``// m=2 n=6`
`        ``// pre -> 1 2 3 4 5 6`
`        ``// current -> 2 3 4 5 6`
`        ``// 反转`
`        ``for` `(``int` `i = m; i < n; i++) {`
`            ``ListNode temp = current.next; ``// temp -> 3 4 5 6`
`            ``current.next = temp.next; ``// 断指针23->24 current -> 2 4 5 6 pre -> 1 2 4 5 6 dummy -> -1 1 2 4 5 6`
`            ``temp.next = pre.next; ``// 断指针34->32  temp ->  3 2 4 5 6 dummy -> -1 1 2 4 5 6`
`            ``pre.next = temp; ``// 连接指针12->13 pre -> 1 3 2 4 5 6  dummy -> -1 1 3 2 4 5 6`
`        ``}`
`        ``return` `dummy.next;`
`    ``}`