牛客题霸--反转链表题解
反转链表
http://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
java版本答案:
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode temp = head; ListNode result = null; if(head == null){ return null; } while(temp.next!=null){ head = temp.next; temp.next = result; result = temp; temp = head; } temp.next = result; result = temp; return result; }
}
链表是c语言里面特有的概念,对于java开发来说可能有点陌生。
用两个结点来完成链表反转的操作,result是存在最终的结果的,temp是存在遍历链表的暂态。
总体思路就是从头链表开始依次遍历,然后采用头插法分别将元素插入到result中。
需要注意的是由于while循环的条件是temp.next != null,因此遍历结束之后,需要将原链表的最后一个结点插入到result中。