包括反转整个链表、从第k个节点开始反转链表
代码如下:
package lianbiaofanzhuang;
class Node
{
int v;
Node next;
public Node(int v,Node next) {
this.next=next;
this.v=v;
}
}
public class T1 {
public static void main(String[] args)
{
int[] data={1,4,5,6,8,0};
Node next=null;
for(int i=data.length-1;i>-1;i--)
{
Node node=new Node(data[i], next);
next=node;
}
Node root=next;
System.out.println("链表为");
printList(root);
Node reverseNode=reverse(root);
System.out.println("整个列表反转");
printList(reverseNode);
System.out.println("从第三个节点开始反转");
Node reverseNodeK=reverseNodeK(reverseNode, 3);
printList(reverseNodeK);
}
//反转链表root
static Node reverse(Node root)
{
Node cur=null;
Node next=root;
Node temp=root==null?null:root.next;
while(next!=null)
{
next.next=cur;
cur=next;
next=temp;
temp=temp==null?null:temp.next;
}
return cur;
}
//从链表的第k个节点饭庄链表(k>=2)
static Node reverseNodeK(Node root,int k)
{
Node cur=root;
Node pre=root;
int i=1;
while(cur!=null)
{
pre=cur;
cur=cur.next;
if(++i==k)
{
break;
}
}
Node reverseNode=reverse(cur);
pre.next=reverseNode;
return root;
}
static void printList(Node root)
{
Node cur=root;
while(cur!=null)
{
if(cur.next!=null)
{
System.out.print(cur.v+"->");
}
else
{
System.out.println(cur.v);
}
cur=cur.next;
}
}
}