删除链表中指定元素 删除指定下标的节点 添加节点 反转链表 输出链表
class ListNode {
int val;
ListNode next;
public ListNode ( int x) {
val = x;
}
}
public class Solution {
public static ListNode removeElements ( ListNode head, int val) {
while ( head != null && head. val == val) {
head = head. next;
}
if ( head == null) {
return null;
}
ListNode prev = head;
while ( prev. next != null) {
if ( prev. next. val == val) {
prev. next = prev. next. next;
} else {
prev = prev. next;
}
}
return head;
}
public static ListNode addNode ( ListNode head, int val) {
ListNode newNode = new ListNode ( val) ;
if ( head == null) {
head = newNode;
return head;
}
ListNode p = head;
while ( p. next != null) {
p = p. next;
}
p. next = newNode;
return head;
}
public static void printListNode ( ListNode head) {
StringBuffer stringBuffer = new StringBuffer ( ) ;
if ( head != null) {
stringBuffer. append ( "{" ) ;
ListNode p = head;
while ( p != null) {
stringBuffer. append ( p. val + "," ) ;
p = p. next;
}
stringBuffer. replace ( stringBuffer. length ( ) - 1 , stringBuffer. length ( ) , "}" ) ;
}
System. out. println ( stringBuffer. toString ( ) ) ;
}
public static ListNode removeIndex ( ListNode head, int index) {
if ( index < 1 || index > length ( head) ) {
return head;
}
if ( index == 1 ) {
head = head. next;
return head;
}
int i = 1 ;
ListNode p = head;
while ( p. next != null) {
if ( i != index) {
p = p. next;
i++ ;
} else {
p. next = p. next. next;
}
}
return head;
}
public static ListNode reverseListNode ( ListNode head) {
if ( head == null) return null;
ListNode reverseNode = null;
if ( head. next == null) {
reverseNode = head;
return reverseNode;
}
ListNode next = null;
while ( head != null) {
next = head. next;
head. next = reverseNode;
reverseNode = head;
head = next;
}
return reverseNode;
}
public static int length ( ListNode head) {
int length = 0 ;
ListNode tmp = head;
while ( tmp != null) {
length++ ;
tmp = tmp. next;
}
return length;
}
public static void main ( String[ ] args) {
Scanner scanner = new Scanner ( System. in) ;
String sin = scanner. nextLine ( ) ;
String[ ] strings = sin. split ( "," ) ;
List< String> linkList = new ArrayList < > ( ) ;
List< String> tarNums = new ArrayList ( ) ;
for ( int i = 0 ; i < strings. length; i++ ) {
if ( strings[ i] . contains ( "[" ) ) {
strings[ i] = String. valueOf ( strings[ i] . charAt ( 1 ) ) ;
}
if ( strings[ i] . contains ( "]" ) ) {
strings[ i] = String. valueOf ( strings[ i] . charAt ( 0 ) ) ;
tarNums = Arrays. asList ( Arrays. copyOfRange ( strings, i + 1 , strings. length) ) ;
linkList = Arrays. asList ( Arrays. copyOfRange ( strings, 0 , i) ) ;
}
}
ListNode result = null;
ListNode head = null;
for ( String s : linkList) {
head = addNode ( head, Integer. valueOf ( s) ) ;
}
for ( String val : tarNums) {
result = removeElements ( head, Integer. valueOf ( val) ) ;
}
printListNode ( result) ;
}
}