删除链表的倒数第 n 个结点,并且返回链表的头结点
方式一,使用普通方法
public class ListNodeDemo2 {
public static void main ( String [ ] args) {
ListNode head = new ListNode ( 1 ) ;
ListNode data1 = new ListNode ( 2 ) ;
ListNode data2 = new ListNode ( 3 ) ;
ListNode data3 = new ListNode ( 4 ) ;
ListNode data4 = new ListNode ( 5 ) ;
data3. next = data4;
data2. next = data3;
data1. next = data2;
head. next = data1;
ListNode listNode = removeNthFromEnd ( head, 2 ) ;
for ( ListNode temp = listNode; temp != null ; temp = temp. next) {
System . out. println ( temp. val) ;
}
}
public static ListNode removeNthFromEnd ( ListNode head, int n) {
ListNode temp = head;
Map < Integer , ListNode > map = new HashMap < > ( ) ;
int index = 1 ;
while ( temp != null ) {
map. put ( index++ , temp) ;
temp = temp. next;
}
int size = map. size ( ) ;
if ( size == 1 )
return null ;
if ( n == 1 ) {
map. get ( size - 1 ) . next = null ;
} else if ( n == size) {
head = head. next;
} else {
map. get ( size - n) . next = map. get ( size - n + 2 ) ;
}
return head;
}
}
方式二,使用双指针思想
public static ListNode removeNthFromEnd ( ListNode head, int n) {
ListNode slow = head;
ListNode fast = head;
while ( n-- != 0 ) {
fast = fast. next;
}
if ( fast == null ) {
return head. next;
}
fast = fast. next;
while ( fast != null ) {
fast = fast. next;
slow = slow. next;
}
slow. next = slow. next. next;
return head;
}
方式三,破坏原有链表结构,构建新的链表
public static ListNode removeNthFromEnd ( ListNode head, int n) {
ListNode newHead = new ListNode ( 0 ) ;
ListNode cur = newHead;
int index = 1 ;
Map < Integer , ListNode > map = new HashMap < > ( ) ;
for ( ListNode temp = head; temp != null ; temp = temp. next) {
map. put ( index++ , temp) ;
}
for ( ListNode listNode : map. values ( ) ) {
listNode. next = null ;
}
map. remove ( map. size ( ) - n + 1 ) ;
for ( ListNode node : map. values ( ) ) {
cur. next = node;
cur = cur. next;
}
return newHead. next;
}