首页 题型归类🔍_链表反转
文章
取消

题型归类🔍_链表反转

1️⃣.从头到尾的链表反转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre =null;
        ListNode curr = head;

        while(curr!=null){
            ListNode next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }
}

2️⃣.给定区间的链表反转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode temp = new ListNode(0,head);
        ListNode pre =temp;

        
		//找到要反转节点 前面那个节点
        int r=1;
        while(r<left){
            pre = pre.next;
            ++r;
        }
        

        ListNode curr = pre.next;
        
        
        
        for(int i=1;i<=right-left;++i){

            ListNode next = curr.next;
            curr.next = next.next;
            next.next = pre.next;
            pre.next = next;

        }

        return temp.next;
    }
}

3️⃣. 2个一组的链表反转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    //两个一组反转链表
    public ListNode swapPairs(ListNode head) {
        ListNode pre = new ListNode(0,head);
        ListNode temp = pre;

        while(pre.next!=null&&pre.next.next!=null){
            ListNode n1 = pre.next;
            ListNode n2 = pre.next.next;

            pre.next = n2;

            n1.next = n2.next;

            n2.next = n1;

            pre = n1;

        }

        return temp.next;

    }
}

4️⃣. k个一组的链表反转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Solution {
    //k个一组反转链表
    public ListNode reverseKGroup(ListNode head, int k) {

        ListNode temp = new ListNode(0,head);
        ListNode end = temp;
        ListNode pre = temp;


        while(end.next!=null){
            
            for(int i=1;i<=k&&end!=null;i++){

                end =end.next;

            }

            if(end==null) break;

            ListNode start = pre.next;

            ListNode next = end.next;

            end.next=null;

            pre.next = reverse(start);

            start.next =next;

            pre =start;

            end =pre;





        }




        return temp.next;

        
    }

    public ListNode reverse(ListNode head){
        ListNode pre = null;
        ListNode curr = head;

        while(curr!=null){
            ListNode next = curr.next;
            curr.next = pre;
            pre=curr;
            curr=next;
        }

        return pre;
    }

}

总结提炼🎯

1
 1️⃣要舍得用指针
本文由作者按照 CC BY 4.0 进行授权

题型归类🔍_股票问题

题型归类🔍_计算器