反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL

输出: 5->4->3->2->1->NULL

遍历实现

三个指针分别指向当前节点和前一个后一个节点,让当前节点的下一个节点从原来的下一个节点改成指向前一个节点,便实现了两个节点的反转,依次遍历就实现了所有节点反转

 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

class ListNode {

    int val;

    ListNode next;



    ListNode(int x) {

        val = x;

    }

}



class Solution {

    public ListNode reverseList(ListNode head) {

        if (head==null) return head;

        ListNode pre = null;

        ListNode cur = head;

        ListNode next = null;

        while (cur.next!=null){

            next = cur.next;

            cur.next = pre;

            pre = cur;

            cur = next;

        }

        return cur;

    }

}

递归实现

暂时还没理解~