Java反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路1:
边遍历边生成,一个临时节点,保存遍历的值生成一个临时节点,加到结果链表头去。
/**
-
Definition for singly-linked list.
-
public class ListNode {
-
int val;
-
ListNode next;
-
ListNode(int x) { val = x; }
-
}
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode re=new ListNode(0);while(head!=null){ ListNode Node=new ListNode(head.val); if(re.next!=null){ Node.next=re.next; } re.next=Node; head=head.next; } return re.next;
}
}
思路2:
反转链表,可以根据栈的后进先出的特点先对链表进行遍历,再根据栈生成链表。
/**
- Definition for singly-linked list.
- public class ListNode {
-
int val;
-
ListNode next;
-
ListNode(int x) { val = x; }
- }
*/
class Solution {
public ListNode reverseList(ListNode head) {
Stack r=new Stack();
ListNode re=new ListNode(0);
ListNode res=re;
while(head!=null){
r.add(head.val);
head=head.next;
}
while(!r.empty()){
ListNode node=new ListNode(r.pop());
res.next=node;
res=res.next;
}
return re.next;
}
}