206.反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
(1)递归
public ListNode reverseList(ListNode head) {
if(head==null)
return head;
if(head.next==null)
return head;
ListNode last=reverseList(head.next);
head.next.next=head;
head.next=null;
return last;
}
(2)迭代
public ListNode reverseList(ListNode head) {
if(head==null)
return head;
ListNode b,c;
c=head;
head=null;
while(c!=null)
{
b=c.next;//先在前面占个位置
c.next=head;//回头看看
head=c;//自已变成头
c=b;//继续向前
}
return head;
}
141.环形链表
这类题注意首尾
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null)
return false;
ListNode man=head;
ListNode kuai=head;//初始
while(kuai!=null&&kuai.next!=null)
{
man=man.next;
kuai=kuai.next.next;
if(man==kuai)
return true;
}
return false;
}
19.删除链表的倒数第 N 个结点
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
public ListNode removeNthFromEnd(ListNode head, int n) {
int a=0,c=0;
ListNode aa = new ListNode(0, head);
ListNode b=aa;
while(head!=null){
a++;
head=head.next;
}
for (int i = 1; i < a - n + 1; ++i)
{
b = b.next;
}
b.next=b.next.next;//只要你记住头节点,那这个链表就还没有消失
ListNode dummy=aa.next;
return dummy;
}
若有错误,欢迎留言。