这两题链表都是关于反转的
206.反转链表
1.用三个指针
Java跟c不同,没有指针的概念,所以访问下一个是用.next的方式。java的空为null
注意空指针问题,链表末端只有一个空值,指向空值.next会发生错误。
/** * 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;
else { ListNode a,b,c;
a=head;
b=a.next;
c=b.next;
a.next=null;
if(c==null)
{ b.next=a;
a.next=null; }
else{
while(c!=null)
{b.next=a;
a=b;
b=c;
c=c.next; }
b.next=a;}
return b;} }}
2.递归(从后往前重复一个动作:p.next.next=p;p.next=null;)
虽然代码会比较少,但是浪费很多空间
public ListNode reverseList(ListNode head){
//停止压栈条件
if(head==null||head.next==null)//包括链表为空的情况
return head;
ListNode p=reverseList(head.next);
head.next.next=head;
head.next=null;
return p;
}
234.回文链表
请判断一个链表是否为回文链表。
要实现空间复杂度为O(1).那就不能用数组存储,先用快慢指针(这个真好用),把中电以后的链表反转,然后就开始逐个比较。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
ListNode reverse(ListNode head)
{if(head==null||head.next==null)
return head;
else {
ListNode a,b,c;
a=head;
b=a.next;
c=b.next;
a.next=null;
if(c==null)
{b.next=a;
a.next=null;}
else{
while(c!=null)
{b.next=a;
a=b;
b=c;
c=c.next; }
b.next=a;}
return b;} }
public boolean isPalindrome(ListNode head) { if(head==null||head.next==null)
return true;
else{
ListNode p=head,q=head.next;
while(q!=null&&q.next!=null)
{p=p.next;
q=q.next.next;}
q=p.next;
p=reverse(q);
q=head;
while(p!=null&&p.val==q.val)
{q=q.next;
p=p.next;}
if(p==null)
return true;
else return false;} }}
来源:CSDN
作者:sigedengpao
链接:https://blog.csdn.net/weixin_43838915/article/details/104578931