剑指offer刷题(十八)

62 阅读1分钟

反转链表

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

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

限制:

0 <= 节点个数 <= 5000

解题思路:
先遍历获取链表长度以及值,在遍历修改值。
java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {

        ListNode p = head;
        ListNode q = head;
        ListNode m = head;
        int math = 0;
        while(p!=null){
            math++;
            p = p.next;
        }
        int[] res = new int[math];
        for(int i =0;i<math;i++){
            res[i]=q.val;
            q = q.next;
        }

        for(int i =math-1;i>=0;i--){
            m.val = res[i];
            m = m.next;
        }
        return head;
    }
}

python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        p = head
        q = head
        res = []
        while p :
            res.append(p.val)
            p = p.next
        while q:
            q.val = res.pop()
            q = q.next
        return head