题目:
输入一个链表,反转链表后,输出链表的所有元素。
这个题目中,head头结点就存放了元素。
思路:
代码:
/*
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 next;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}
另一种思路:
头结点不用来存放元素,也就是从head.next开始存放元素。
代码:
class Solution1 {
public ListNode ReverseList(ListNode head) {
if(head==null) {
return null;
}
ListNode p=head.next;
ListNode q;
while(p.next!=null) {
q=p.next;
p.next=q.next;
q.next=head.next;
head.next=q;
}
return head;
}
}