1、题目描述
给定一个单链表的头结点pHead,长度为n,反转该链表后,返回新链表的表头。
?
2、算法分析
链表得反转:
定义结点pre,p,pre指向得是前一个结点,p指向当前结点。
ListNode pre = null;
ListNode p = head;
遍历链表:
p指针先指向head的下一个结点; p = head.next
head反转方向?head.next = pre;
然后pre,head都往后走:pre指向head指向的结点,head指向的是p结点
pre = head ; head = p;
之后p结点再head.next
p = head.next;
head再反转方向:head.next = pre。
循环,直到head.next = null
3、代码实现
/*
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 pre = null;
ListNode p = head;
while(head != null){
p = head.next;
head.next = pre;
pre = head;
head = p;
}
return pre;
}
}
|