反转一个单链表

原题

  Reverse a singly linked list.算法

题目大意

  反转单链表。spa

解题思路

  使用头插法。.net

代码实现

结点类code

public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

算法实现类get

public class Solution {

    public ListNode reverseList(ListNode head) {
        // 头结点
        ListNode root = new ListNode(0);
        ListNode nextNode;
        while (head != null) {
            nextNode = head.next;
            head.next = root.next;
            root.next = head;
            head = nextNode;
        }

        return root.next;
    }
}
相关文章
相关标签/搜索