题目:
输入一个链表,反转链表后,输出新链表的表头。
思路:
取两个指针,pre和nex分别保存 当前节点head的前一个节点和后一个节点。
输入:1>2>3>4
(1)pre>null
head=1 ,pre,nex=null,先保存head.next的信息到nex(2),然后让head.next指向pre(null),pre指向head(1),head指向nex(2)。
输出:null<1 2>3>4 , 有pre>1
(2)
head=2 ,pre=1,nex=2,先保存head.next的信息到nex(3),然后让head.next指向pre(1),pre指向head(2),head指向nex(3)。
输出:null<1<2 3>4,有pre>2
(3)…这里pre就是新链表的表头
/*
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 nex=null;
while(head!=null)
{
nex=head.next;
head.next=pre;
pre=head;
head=nex;
}
return pre;
}
}