Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
public ListNode reverseList(ListNode head) {
if (head == null || head.next ==null) return head;
ListNode pre = null;
ListNode cur = head;
ListNode next = head.next;
while (cur !=null&&next !=null){
cur.next = pre;
pre = cur;
cur = next;
next = next.next;
}
cur.next = pre;
return cur;
}
这个解法与解法一的区别在于对next何时进行更新,如何更新。
public ListNode reverseList(ListNode head) {
if (head == null || head.next ==null) return head;
ListNode pre = null;
ListNode cur = head;
ListNode next;
while (cur !=null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
注意细节的处理。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。