题目描述:
反转一个单链表。
示例1:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
思路:
迭代:在遍历列表时,将当前节点的next 指针改为指向前一个元素。由于节点没有引用其上一个节点,所以需先存储其前一个元素以。在修改指针之前,还需要另一个指针来存储下一个节点。
代码实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(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;
cur = next;
}
return pre;
}
}