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?
public ListNode reverseList(ListNode head) {//链表 迭代 my
ListNode nhead = null;
ListNode curr = head;
while(null!=curr){
head=head.next;
curr.next=nhead;
nhead=curr;
curr=head;
}
return nhead;
}
递归
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
进阶题
两两交换链表中的结点 LeetCode24 https://www.cnblogs.com/zhacai/p/10559271.html
每 k 个节点一组翻转链表 LeetCode25 https://www.cnblogs.com/zhacai/p/10563446.html