题目:反转链表
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
解题过程:
代码:
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class Solution{
public ListNode reverseList(ListNode head) {
ListNode prev =null;//定义前驱结点,虽然现在为空
ListNode cur = head;//当前结点为头节点
while(cur!=null){
ListNode next=cur.next;//定义后继结点
cur.next=prev;//改变引用指向的对象
prev=cur;//前驱结点后移
cur=next;//当前结点后移
}
return prev;//返回头节点
}
//测试方法能否反转链表
public static void main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
n1.next = n2;
n2.next = n3;
n3.next = null;
for (ListNode cur = reverseList(n1); cur != null; cur = cur.next) {
System.out.println(cur.val);
}
}
}