单链表反转
输入一个链表,反转链表后,输出新链表的表头。
第一种用了四个指针,没有下一个简单
public class Solution { public ListNode ReverseList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode cur = head; ListNode p = head.next; while (p != null) { ListNode q = p.next; p.next = cur; cur = p; p = q; } head.next = null; return cur; } } class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }
这个解发用了三个,比较好
public class Solution { public ListNode ReverseList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode cur = head.next; head.next = null;//第一个节点变成尾节点,指向null // 下面是大于1个节点的情况 while (cur != null) { ListNode temp = cur.next; cur.next = head; head = cur; cur = temp; } return head; } } class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }