题目描述
输入一个链表,反转链表后,输出新链表的表头。
解题思路
设置结点p与res,p结点用于指向下一节点,head是移动结点,将head.next不断指向前一个结点。并且p不断向后移动,res为记录当前所在结点,最后得到res,即为反转后的链表头节点
源码
/*
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)
return null;
ListNode p =head.next;
ListNode res = null;
while(head!=null){
head.next = res;
res = head;
head = p;
if(head != null)
p = head.next;
}
return res;
}
}