package com.niuke;
/**
* Created by admin on 2018/3/5.
*/
public class ReverseList {
//循环非递归方法
// 1->2->3->4
//变为 1 2->3->4
// 1<-2 3->4
// 1<-2<-3 4
// 1<-2<-3<-4 pre节点即为最后一个节点
public ListNode ReverseList(ListNode head) {
ListNode pre=null;
ListNode next=null;
while(head!=null) {//循环找到最后一个节点
next=head.next;
head.next=pre;//此时head没有指向下一个的句柄
pre=head;
head=next;
}
return pre;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
输入一个链表,反转链表后,输出链表的所有元素。
最新推荐文章于 2018-08-28 09:46:49 发布