链表逆置
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
解题
头插法简单明了 code
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
| public class ReverseList {
public static class ListNode { int val; ListNode next;
ListNode(int x) { val = x; } }
public ListNode getReverseList(ListNode head) { ListNode newList = new ListNode(-1); while (head != null) { ListNode nextNode = head.next; head.next = newList.next; newList.next = head; head = nextNode; } return newList.next; } }
|