剑指Offe6-反转链表
输入一个链表,反转链表后,输出新链表的表头。
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode pre=null; //指向当前结点前面的那个结点
ListNode next=null;//指向当前结点后面的那个结点
if(head==null)
return null;
/* 1->2->3->4 变成 1<-2 3->4 */
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}