节点信息类
public class ListNode {
int val;
ListNode next ;
public ListNode(int val) {
this.val = val;
}
}
ListNode head = new ListNode(6);
// 初始化链表内容
private void initList() {
ListNode temp = head;
head.next = null;
for(int i = 5;i>0;i--){
ListNode node = new ListNode(i);
node.next = null;
temp.next = node;
temp = temp.next;
}
StringBuilder print = print(head);
}
/**
* 打印链表 信息
* @param head 头节点Node
* @return
*/
private StringBuilder print(ListNode head) {
StringBuilder sb = new StringBuilder();
// ListNode temp = head;
while (head.next != null){
sb.append(head.val+" ->");
head = head.next;
}
sb.append(head.val+" ->NULL");
Log.e("TAG",sb.toString());
return sb;
}
/**
* 反转链表
* @param head
* @return
*/
public ListNode reverseList(ListNode head) {
ListNode pre = null,
cur = head,
next = null;
while (cur != null){
// 下一个节点赋值
next = cur.next;
// 上一个节点赋值
cur.next = pre;
// ---- 把当前节点当做前一个 下一个节点当做当前节点 进入下一次循环
pre = cur;
cur = next;
}
return pre;
}
下边是android 验证的activity 代码
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// handler.sendEmptyMessage(0);
textView = (TextView) findViewById(R.id.tv);
textView.setText("舒适化");
initList();
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Reverse();
}
});
}
private void Reverse() {
ListNode listNode = reverseList(head);
print(listNode);
}
ListNode head = new ListNode(6);
private void initList() {
ListNode temp = head;
head.next = null;
for(int i = 5;i>0;i--){
ListNode node = new ListNode(i);
node.next = null;
temp.next = node;
temp = temp.next;
}
StringBuilder print = print(head);
// textView.setText(print);
}
/**
* 打印链表 信息
* @param head 头节点Node
* @return
*/
private StringBuilder print(ListNode head) {
StringBuilder sb = new StringBuilder();
// ListNode temp = head;
while (head.next != null){
sb.append(head.val+" ->");
head = head.next;
}
sb.append(head.val+" ->NULL");
Log.e("TAG",sb.toString());
return sb;
}
/**
* 反转链表
* @param head
* @return
*/
public ListNode reverseList(ListNode head) {
ListNode pre = null,
cur = head,
next = null;
while (cur != null){
// 下一个节点赋值
next = cur.next;
// 上一个节点赋值
cur.next = pre;
// ---- 把当前节点当做前一个 下一个节点当做当前节点 进入下一次循环
pre = cur;
cur = next;
}
return pre;
}
}