一、反转链表(力扣206)
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
1、头插法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode dummy = new ListNode(-1,head);
ListNode temp;
if(head==null){
return head;
}
ListNode current=head.next;
head.next=null;
while(current!=null){
temp=current.next;
current.next=dummy.next;
dummy.next=current;
current=temp;
}
return dummy.next;
}
}
2、双指针法
注意:最后返回新链表的头结点!!!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
ListNode temp;
//遍历的过程 什么时候遍历结束 cur==null时 遍历结束
while(cur!=null){
temp = cur.next;
cur.next=pre;
pre = cur;
cur = temp;
}
return pre; //返回新链表的头结点 此时pre是当前新链表的头结点 不再是head!
}
}
3、递归法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
return reverse(null,head);
}
public ListNode reverse(ListNode pre,ListNode cur){
if(cur==null){
return pre; //新链表的头结点
}
ListNode temp;
temp = cur.next;
cur.next=pre;
return reverse(cur,temp);
}
}
二、回文链表(力扣234)
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
如果再定义一个新的链表,实现链表元素的反转,然后进行比较:
但是运行有错:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode oldHead = head;
ListNode newHead = reverse(oldHead);
while(newHead!=null&&head!=null){
if(newHead.val!=head.val){
return false;
}
head=head.next;
newHead=newHead.next;
}
return true;
}
public ListNode reverse(ListNode head){
ListNode cur=head.next;
ListNode pre = null;
ListNode temp;
while(cur!=null){
temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
return pre;
}
}
未解决!