反转链表
输入一个链表,反转链表后,输出新链表的表头。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode ReverseList(ListNode head) {
//老规矩,处理特殊情况。
if(head == null || head.next == null)
return head;
ListNode p = null;
ListNode q = head;
ListNode s = q.next;
while(q != null){
q.next = p;
//仔细看这个退出条件哟
if(s == null)
break;
p = q;
q = s;
s = s.next;
}
return q;
}
}
我个人觉得这个从尾到头打印链表更值得研究,故这个代码不做解释啦!
https://blog.csdn.net/dream_one_day/article/details/97032156