Description
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution
就新建一个头结点,然后遍历原链表,使用头插法搬到新链表中。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode p = head;
ListNode newHead = new ListNode(0);
newHead.next = null;
while(p != null){
ListNode q = p;
p = p.next;
q.next = newHead.next;
newHead.next = q;
}
return newHead.next;
}
}
来源:CSDN
作者:jxnu_毛毛
链接:https://blog.csdn.net/weixin_41317766/article/details/104038298