链表操作是我非常不擅长的一种题型,所以如果遇到有相关的题目就记一下。
Leetcode 206
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
//非递归
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode pre=head,p=head.next;
pre.next=null;
while(p!=null)
{
//pre.next=null;
ListNode temp=p.next;
p.next=pre;
pre=p;
p=temp;
}
return pre;
}
}
//递归
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode pre=reverseList(head.next);
head.next.next=head;
head.next=null;
return pre;
}
}