//反转链表,带头结点
public static ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = new ListNode(-1);
ListNode newTmp = null;
ListNode tmp = head.next;
while (tmp != null) {
ListNode next = tmp.next;//需要有一个变量指向下一个结点的位置,防止丢失
tmp.next = newHead.next;
newHead.next = tmp;
tmp = next;
}
head = newHead;
return head;
}
//没有头结点
public static ListNode reverseList02(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;//每来一个新的结点,就将其设置为第一个结点结点
pre = cur;//pre指向第一个结点
cur = next;
}
return pre;
}
反转单链表的思路及JAVA代码
最新推荐文章于 2023-08-17 15:01:30 发布