package Test;
import java.util.Stack;
/*public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Test2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode head=new ListNode(0);
ListNode[] list=new ListNode[5];
for (int i = 0; i < list.length; i++) {
list[i]=new ListNode(i);
if(i>0){
list[i-1].next=list[i];
}else{
head.next=list[0];
}
}
Test2 test=new Test2();
ListNode result=test.plusAB(head, head);
System.out.println(result.val);
}
/*
* 输入一个链表,输出该链表中倒数第k个结点。
*/
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null || k<=0) return null;
ListNode p1=head;
ListNode p2=head;
for (int i = 0; i <k-1; i++) {
if(p1==null) return null;
p1=p1.next;
}
if(p1==null) return null;
while(p1.next!=null){
p1=p1.next;
p2=p2.next;
}
return p2;
}
/*
* 实现一个算法,删除单向链表中间的某个结点,假定你只能访问该结点。
给定带删除的节点,请执行删除操作,若该节点为尾节点,返回false,否则返回true
*/
public boolean removeNode(ListNode pNode) {
// write code here
if(pNode.next==null) return false;
ListNode p=pNode.next;
pNode.next=p.next;
pNode.val=p.val;
return true;
}
/*
* 编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
*/
public ListNode partition(ListNode pHead, int x) {
// write code here
if(pHead==null||pHead.next==null) return pHead;
ListNode left=new ListNode(0);
ListNode right=new ListNode(0);
ListNode head=left;
ListNode head2=right;
while(pHead!=null){
if(pHead.val<x){
left.next=pHead;
left=left.next;
}else{
right.next=pHead;
right=right.next;
}
pHead=pHead.next;
}
left.next=head2.next;
right.next=null;
return head.next;
}
/*
* 有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。
给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。
测试样例:
{1,2,3},{3,2,1}
返回:{4,4,4}
{7,4,0,7,5} {2,7,2,3,4}
返回{9,1,3,0,0,1}
*/
public ListNode plusAB(ListNode a, ListNode b) {
// write code here
if(a==null) return b;
if(b==null) return a;
ListNode list=new ListNode(0);
ListNode head=list;
int sum=0;
while(a!=null || b!=null){
if(a!=null){
sum+=a.val;
a=a.next;
}
if(b!=null){
sum+=b.val;
b=b.next;
}
list.next=new ListNode(sum%10);
list=list.next;
sum/=10;
}
if(sum==1){
list.next=new ListNode(1);
}
return head.next;
}
/*
* 请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
*/
public boolean isPalindrome(ListNode pHead) {
// 利用 stack 堆栈的特性 后进先出 反转
Stack s=new Stack();
ListNode list=pHead;
while(pHead!=null){
s.push(pHead.val);
pHead=pHead.next;
}
while(list!=null){
if((int)s.pop()==list.val){
list=list.next;
}else{
return false;
}
}
return true;
}
}
编程2(链表)
最新推荐文章于 2019-05-27 17:40:04 发布